Here is a simple counting code to count from 14 to 0 using setInterval
.
After 3 seconds I want to clear the interval and stop counting using savedTimerCounter('stop');
.
The problem is I can't access the interval to clear it at savedTimerCounter('stop');
Why and how to fix this? What I'm missing?
let savedTimer;
function savedTimerCounter(el) {
//function scope variable
switch (el) {
case 'start':
timeleft = 14;
console.log(timeleft);
savedTimer = setInterval(function() {
timeleft--;
console.log(timeleft);
if (timeleft <= 0) {
clearInterval(savedTimer);
console.log("done");
return;
}
}, 1000);
break;
case 'stop':
clearInterval(savedTimer);
break;
}
}
//Start counting
savedTimerCounter('start');
//Stop counting that dosn't work!
setTimeout(function() {
savedTimerCounter('stop');
}, 3000)
If you put the let savedTimer;
outside of the function (Why?) the code works but as it's a bad practice to create global variables I want a hint here...