I am trying to set up some delays on a loop using incremental IDs in my function call, as well as incrementally larger delay times. What I have set up is like this:
var delay = 0;
var delayMilliseconds = 250;
timeOutArray = [];
for(var i=0; i<100; i++){
delay = i*delayMilliseconds;
timeOutArray[i] = setTimeout(function(){
loadRoute(modelsArray[i], (i+1));
},delay);
}
The problem I am running into is that by the time any of the loadRoute() functions get called, the "i" being referenced has already been incremented to 99.
I am looking for a way to make it recognize the number of "i" at the moment I set the Timeout, rather than the moment the Timeout occurs.
I found this article about using "promises", but is a bit confusing. Javascript - Wait the true ending of a function that uses setTimeout
Could someone please show me know to implement promises into these calls, or anything that can do it without wrapping the setTimeout code all in an eval()?
This is the working example of your code. The problem is misunderstanding of Scope & Closure.
var delay = 0;
var delayMilliseconds = 250;
timeOutArray = [];
for (var i=1; i<100; i++) {
(function(j){
delay = j*delayMilliseconds;
timeOutArray[j] = setTimeout(function(){
console.log(j)
//loadRoute(modelsArray[j], (j+1));
},delay);
})( i );
}
Explanation:
(function(j){
//this part of the code create new scope
})( i );
The use of above function inside each iteration created a new scope for each iteration, which gave our timeout function callbacks the opportunity to close over a new scope for each iteration, one which had a variable with the right per-iteration value in it for us to access.