Javascript function does not respect loop conditions

3

Good afternoon, I'm new here and I'm using Mozilla Firefox JavaScript Scratchpad to run Javascript tags. It will really suit my needs, however the while loop condition of the while loop is not working (for also did not work). Also, the variable i is not having its value incrementing, preventing any value beyond the first of array from being used. Thanks for any response, thank you.

Follow the code:

window.setInterval(function () {
   var inputs = [ 10595, 10243, 11514, 11053, 10449, 10208, 11160, 10970, 10706, 11075, 10400, 10112, 10086, 10503, 11910, 12110, 11537, 9694, 12112, 10793, 11728, 9532, 10389, 12983, 9533, 12424, 10697, 11997, 12121, 11606, 10526, 9729, 10143, 11737, 10025, 10700, 11564, 12623, 9324, 11761, 10008, 11780, 10105, 12230, 12489, 12649, 9083, 11192, 10010, 10984, 12075, 12075, 11026, 12194, 12335, 10035];
    var i = 0;
    do {
        Accountmanager.farm.sendUnits(this, inputs[i], 4202);
        i++;
    }
    while (i < 5)
}, 250);
    
asked by anonymous 23.10.2015 / 20:25

3 answers

3

If I understand correctly you want to pass the values of this array one by one with a range of 250 ms between them.

You can do it like this:

function processar(dados, delay) {

    var arr = dados.slice();
    function enviar() {
        var proximo = arr.shift();
        Accountmanager.farm.sendUnits(this, proximo, 4202);
        if (arr.length) setTimeout(enviar, delay);
    }
    setTimeout(enviar, delay);
}

The idea is to create a function that processes this submission. Each line var arr = dados.slice(); creates a copy of the array so you do not lose the original.

This solution uses setTimeout instead of setInterval which never ends until a clearInterval is called.

To start the upload you can processar(inputs, 250); where you choose what you upload and choose the speed too.

Example: link

    
23.10.2015 / 21:15
4

The loop is running correctly but you are externally using the setInterval function that re-runs the function every 250 milliseconds, if you want to send all the items in your array, you can pass the size of it in the while condition.

// código do seu array omitido

var i = 0;
do {
    Accountmanager.farm.sendUnits(this, inputs[i], 4202);
    i++;
} while (i < inputs.length)

Example with the value of each item: link

    
23.10.2015 / 20:38
0

Personal I received many comments in a very short time, I did not expect all this support, thank you, my problem was solved. The final code I'm using is:

window.setInterval(function () {
    Accountmanager.farm.sendUnits(this, inputs.shift(), 4202);
}, 250);

It was probably this shift () that makes the whole array run, I did not know:)

You can close the topic, thank you.

    
23.10.2015 / 21:05