Why Clearinterval Doesn't Work On A Function
Solution 1:
It doesn't work on a function because that's just now how the mechanism was designed. Calls to setInterval()
return a number that acts as an identifier for the timer that the call establishes. That number is what has to be passed to clearInterval()
.
It doesn't cause an error to pass something that's not a number, or to pass a number that doesn't identify an active timer, but the call has no effect.
In your case, your t()
function could simply return the result of the setInterval()
call, and your outer code can save that for use later however you like.
Solution 2:
It's because you need to return the id of the interval and clear that id.
According to the documentation:
setInterval returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
//function that keeps logging 'hello' on the consolevart = ()=>{
//return the id of the intervalreturnsetInterval(()=>{
console.log('hello')
},1000)
}
//get the id of the interval created by the "t" functionvar id = t();
//alerts the id just to see italert(id);
//clear it - function will stop executingclearInterval(id);
References
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
Solution 3:
because you should clearInterval on reference for setInterval().
var interval = setInterval();
clearInterval(interval);
Solution 4:
T is not equal to the setInterval returned value as you don't return a value from your arrow function, and don't assign it to a value.
Try this snippet instead:
vart = ()=>
setInterval(()=>{
console.log('hello')
},1000)
var interval = t();
clearInterval(interval);
Solution 5:
let intervalId = null;
cycle(true);
functioncycle(r) {
letmyInterval = () => {
returnsetInterval(() =>plusSlides(1), 1000);
}
if (!r) {
clearInterval(intervalId);
} else {
intervalId = myInterval();
}
}
Post a Comment for "Why Clearinterval Doesn't Work On A Function"