+ 1
[Solved] How to stop setInterval method inside of a function
https://code.sololearn.com/WxlP08iSoXs2/?ref=app Hello, I can't stop a setInterval that I called using a function, how to stop this? const laugh = () => { setInterval(() => { console.log("haha"); },5000) } laugh(); setTimeout(() => {clearInterval(laugh);},10000) I also tried making a parameter on laugh() but things gets worst. ClearInterval(laugh(stop)); stop is a parameter inside of laugh() and I assigned setInterval to that stop, so I assumed ClearInterval(laugh(stop)); will make it stop, but what happen is, it creates another setInterval which make it more frequently laughing 😂, this one is laughing non-stop, please, I'm pissed 😡 (JOKE), early thanks for helping.
2 Réponses
+ 3
clearInterval() uses the ID that was returned by setInterval(). So you need to have that ID stored somewhere (in a variable), that can be accessed when we want to stop the interval.
let timerID = null;
const laugh = () =>
{
timerID = setInterval( () =>
{
console.log( "I'm unstoppable'" );
}, 1000 );
}
laugh();
setTimeout( () =>
{
clearInterval( timerID );
console.log( "Yeah right ..." );
}, 10000 );
+ 1
Ipang thanks I now understand how it works 😄