0

I am trying to use the value of a for loop counter inside a queued function, for example:

for(var i=0; i<5; i++)
   $(document.body).queue(function(){alert('i=' + i); $(this).dequeue();}).delay(1000);

then I get:

i=0, i=5, i=5, i=5, i=5

I think this is because i has changed while delay(1000)..
What can I do to get the right values of i, i.e:

 i=0, i=1, i=2, i=3, i=4
Mohsin
  • 513
  • 1
  • 5
  • 12
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake – Arun P Johny Apr 06 '14 at 11:51

1 Answers1

0

Using a closure e.g:

for (var i = 0; i < 5; i++)
    $(document.body).queue(returnFromQueue(i)).delay(1000);

function returnFromQueue(i) {
    return function () {
        alert('i=' + i);
        $(this).dequeue();
    }
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155