Stop setInterval call in JavaScript

前端 未结 16 1814
星月不相逢
星月不相逢 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:56

    clearInterval()

    Note, you can start and pause your code with this capability. The name is a bit deceptive, since it says CLEAR, but it doesn't clear anything. It actually pauses.

    Test with this code:

    HTML:

    100

    JavaScript:

    let count;
    
    function start(){
     count = setInterval(timer,100)  /// HERE WE RUN setInterval()
    }
    
    function timer(){
      document.getElementById('count').innerText--;
    }
    
    
    function stop(){
      clearInterval(count)   /// here we PAUSE  setInterval()  with clearInterval() code
    }

提交回复
热议问题