问题
I've got some rather complicated logic:
var myArray = [];
var tempInterval = 0;
// Run for 6 minutes
for(i=0;i<360;i++) {
// Closure so that 'i' is the right value when setInterval runs
tempInterval = (function(i) {
interval1 = setInterval(function() {
console.log(i);
}, (i * 1000));
return interval1;
})(i);
// Put the setInterval value into an array
myArray.push(tempInterval);
}
I use a Closure because I need the value of i to be 0,1,2,...etc, and if you don't use a closure, it'll be 360 by the time the interval executes.
If you run that in your console, you'll see it runs way more than 360 times. For some reason, it's creating too many intervals.
I want to have a function to stop this execution of setIntervals:
for(i=0; i<myArray.length; i++) {
clearInterval(myArray[i]);
}
But, because it creates too many, I can't get it to stop.
For example, if you run it inside for(i=0; i<5; i++) instead of for(i=0;i<360;i++), you'll see, it still runs indefinitely.
Why is it creating so many intervals, and how do I get it to run only 360 times? Also, is that the right way to save the intervals, so I can use clearInterval to stop their execution?
回答1:
The problem
setInterval does not mean "sleep", it means "Run this function every time period".
Each of the 360 times you go around the loop, you call setInterval saying "Run this function every i seconds.
So you get 360 countdowns, each of which runs a function when it hits zero before restarting the countdown to run the function again.
The solution
Don't use setInterval. Use setTimeout.
Or, alternatively:
I'd generally avoid setting 360 timers running at once and instead do something like:
var i = 0;
function next() {
console.log(i);
i++;
if (i < 360) {
setTimeout(next, 1000);
}
}
next();
来源:https://stackoverflow.com/questions/21212465/setinterval-inside-a-closure-inside-a-for-loop-creates-too-many-intervals-won