I got some problem with setInterval & clearInterval.
In my code, I set multiple intervals, and when count reduce to 0, stop the execution.
Like below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0" charset="utf-8">
</head>
<body>
<body>
<script type="text/javascript">
for (var i=0; i<4; i++){
var count = 100;
var IntervalID = window.setInterval((function(){ // closure
var timeoutID = IntervalID; // temp
var countTemp = count; // temp
var id = i;
return function(){
countTemp --;
console.log(id + " " + countTemp);
// do something here
if ( countTemp == 0 ){
clearInterval(timeoutID); // stop the execution
console.log(id + " stop");
}
}
})(), 20);
}
</script>
</body>
</html>
After the console appear the stop message "x stop", all element stop except the last element(id:3), it still going.
I try to write my code in another form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0" charset="utf-8">
</head>
<body>
<script type="text/javascript">
for (var i=0; i<4; i++){
doSomething(i);
}
function doSomething(id){
var count = 100;
var IntervalID = window.setInterval((function(){ // closure
var timeoutID = IntervalID; // temp
var countTemp = count; // temp
return function(){
countTemp --;
console.log(id + " " + countTemp);
// do something here
if ( countTemp == 0 ){
clearInterval(timeoutID); // stop the execution
console.log(id + " stop");
}
}
})(), 20);
}
</script>
</body>
</html>
But this time, all elements don't stop.
I have two questions:
1. What is difference between these two code?
2. How to make the code work fine?
Edit:
If you just want to make the code work, only change one line in the second snippet:
clearInterval(timeoutID); // stop the execution
to
clearInterval(IntervalID); // stop the execution
But other people's answer can solve what I confuse at this problem.
timeoutIDis undefined fori==0, since the call to setInterval hasn't completed yet. Thus, addingconsole.log(i + " - " + IntervalID);immediately abovevar timeoutID = IntervalID; // tempwill show you0 - undefined, then1 - 1,2 - 2,3 - 3countTempreduce to 0,clearInterval(timeoutID);actually stop previous one (inid==1section, it stopid==0execute;id==2stopid==1; etc. But no one stopid==3, so it still going).