0

I am trying to loop trying to loop through an array in javascript, (jQuery), and pass each key to a separate function.

This works fine, except when I want to factor in a half second delay between function calls for flood protection. When I do this it stops functioning as expected, and only passes the last key to the function instead of the current one?

Please see my simplified example:

$( document ).ready(function() {
    var arr = ['1','2','3','4','5','6','7','8','9'];
    var delay = 500;
    for (var i = 0; i < arr.length; i++) {
        key = arr[i];
        delay = 500 + delay;
        setTimeout(function(){
            output( key );
        }, delay );
    }
});

function output( val ) {
    $('#results').append( val );
}

Expected

123456789

Produced

999999999

Stranger still...

I assumed that this was because the 'key' value was being overwritten each loop, so by the time the Timeout functions trigger, the 'key' is always set to '9'. So I tried not overwriting 'key', but using an array and setting a new 'key' each time, like so:

$( document ).ready(function() {
    var arr = ['1','2','3','4','5','6','7','8','9'];
    var delay = 0;
    var key = [];
    for (var i = 0; i < arr.length; i++) {
        delay++;
        key[delay] = arr[i];
        setTimeout(function(){
            output( key[delay] );
        }, 500*delay );
    }
});

function output( val ) {
    $('#results').append( val );
}

This still produces the result:

999999999

So:

  • Why does this happen when 'key[delay]' should be a different value each time 'delay' is incremented and the Timeout function is set?

  • How can I achieve the results that I am trying to, where the key is different each time the Timeout function is triggered?

Neil Hillman
  • 355
  • 4
  • 17

0 Answers0