Reputation: 25392
I have the following function in a for-loop:
loops.push(setInterval(function(){
showNext(i);
}, 5000));
i
is the index of the for-loop. A problem arises when the push function is run, however. i
is always set to the last index of the for-loop because by the time the interval function is called, the for-loop has finished executing.
How can I make the interval receive the index of the for-loop that it is on now, rather than have it set to the last index of the for-loop?
Upvotes: 1
Views: 77
Reputation: 160883
Use Function.prototype.bind() is much simple:
// the first parameter of bind is not important in this case.
loops.push(setInterval(showNext.bind(this, i), 5000));
Note .bind
need a Polyfill for old browsers.
Upvotes: 0
Reputation: 7632
You can bind i
as an argument to your function:
loops.push(setInterval(showNext.bind(this, i), 5000));
Are you sure by using setInterval instead of setTimeout?
Upvotes: 1
Reputation: 18354
By adding a closure. Like this:
for(var i=0; i<n; i++){
(function(i){
loops.push(setInterval(function(){
showNext(i);
}, 5000));
})(i);
}
This way, the internal i
is different to the external one. This is the same but more understandable:
for(var i=0; i<n; i++){
(function(x){
loops.push(setInterval(function(){
showNext(x);
}, 5000));
})(i);
}
In this way, there's a different x
per loop cycle. As it's no longer shared, it doesn't get overwritten.
Cheers, from La Paz, Bolivia
Upvotes: 2