[Solved] How to stop setInterval method inside of a function | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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.

3rd Jun 2022, 3:07 AM
Jonathan P. Jundarino
Jonathan P. Jundarino - avatar
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 );
3rd Jun 2022, 3:43 AM
Ipang
+ 1
Ipang thanks I now understand how it works 😄
3rd Jun 2022, 3:51 AM
Jonathan P. Jundarino
Jonathan P. Jundarino - avatar