Stop setInterval call in JavaScript

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

    Try

    let refresch = ()=>  document.body.style= 'background: #'
      +Math.random().toString(16).slice(-6);
    
    let intId = setInterval(refresch, 1000);
    
    let stop = ()=> clearInterval(intId);
    body {transition: 1s}
    <button onclick="stop()">Stop</button>

    0 讨论(0)
  • 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:

    <div id='count'>100</div>
    <button id='start' onclick='start()'>Start</button>
    <button id='stop' onclick='stop()'>Stop</button>
    

    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
    }

    0 讨论(0)
  • 2020-11-21 05:58

    If you set the return value of setInterval to a variable, you can use clearInterval to stop it.

    var myTimer = setInterval(...);
    clearInterval(myTimer);
    
    0 讨论(0)
  • 2020-11-21 05:58

    @cnu,

    You can stop interval, when try run code before look ur console browser (F12) ... try comment clearInterval(trigger) is look again a console, not beautifier? :P

    Check example a source:

    var trigger = setInterval(function() { 
      if (document.getElementById('sandroalvares') != null) {
        document.write('<div id="sandroalvares" style="background: yellow; width:200px;">SandroAlvares</div>');
        clearInterval(trigger);
        console.log('Success');
      } else {
        console.log('Trigger!!');
      }
    }, 1000);
    <div id="sandroalvares" style="background: gold; width:200px;">Author</div>

    0 讨论(0)
提交回复
热议问题