Stop setInterval call in JavaScript

前端 未结 16 2176
星月不相逢
星月不相逢 2020-11-21 05:00

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the us

16条回答
  •  生来不讨喜
    2020-11-21 05:35

    var keepGoing = true;
    setInterval(function () {
         if (keepGoing) {
            //DO YOUR STUFF HERE            
            console.log(i);
         }
         //YOU CAN CHANGE 'keepGoing' HERE
      }, 500);
    

    You can also stop the interval by adding an event listener to let's say a button with the ID "stop-interval":

    $('buuton#stop-interval').click(function(){
       keepGoing = false;
    });
    

    HTML:

    
    

    Note: The interval will still be executed, nothing will happen though.

提交回复
热议问题