Reputation: 41
I'm attempting to cancel multiple timers - here's my code :
timer1 = setInterval(func1,3000)
stopper=999
count=5
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1)
clearInterval(timer2)
}else{ //if count bigger than 0
timer2 = setInterval(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
}
}
}
When stopper
hits 0
, it stops writing "Called Func1", but it's still writing "Called Func2" over and over even if stopper
is -999
- how do I stop looping this double setInterval?
Upvotes: 2
Views: 61
Reputation: 1507
The reason this happens is every time func1 is called a new setInterval is being added to the stack.
One possible solution to this would be to replace setInterval for timer2 with setTimeout.
timer1 = setInterval(func1,3000)
stopper=999
count=5
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1)
clearTimeout(timer2)
}else{ //if count bigger than 0
timer2 = setTimeout(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
}
}
}
The second solution would be to clear the timer2 before setting a new one.
timer1 = setInterval(func1,3000)
stopper=999
count=5
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1)
clearInterval(timer2)
}else{ //if count bigger than 0
timer2 = setInterval(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
clearInterval(timer2)
}
}
}
Hope this helps :)
Upvotes: 1
Reputation: 16908
The reason is that the timer2
is being overwritten every time by a new id of the setInterval
call when the setInterval(func2,3000)
is called from func1
.
You are setting up a setInterval
for func1
in the beginning it schedules several setInterval
calls for the func2
in the else
block. The func1
is being invoked 5 times and a separate setInterval
for the func2
is setup for each func1
call.
Now there are multiple intervals set-up for func2
with multiple ids
and each time this happens the timer2
is overwritten with the latest value of the id.
So when the count
reaches 0
it actually cancels one such interval id setup for func2
and the others still continue to run.
You can maintain an array to capture the ids from the setInterval
calls for func2
and cancel them all when count
reaches 0:
(function(){
const timer1 = setInterval(func1,3000)
let stopper = 999
let count = 5
const timerIds = [];
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1);
timerIds.forEach(id => clearInterval(id));
}else{ //if count bigger than 0
timerIds.push(setInterval(func2,3000));
function func2(){
count = count - 1
console.log("Called Func2 " + stopper)
stopper = count
}
}
}
})();
Upvotes: 0