Stop setInterval call in JavaScript

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

    You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:

    var intervalId = null;
    var varCounter = 0;
    var varName = function(){
         if(varCounter <= 10) {
              varCounter++;
              /* your code goes here */
         } else {
              clearInterval(intervalId);
         }
    };
    
    $(document).ready(function(){
         intervalId = setInterval(varName, 10000);
    });
    

    I hope that it helps and it is right.

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

    Declare variable to assign value returned from setInterval(...) and pass the assigned variable to clearInterval();

    e.g.

    var timer, intervalInSec = 2;
    
    timer = setInterval(func, intervalInSec*1000, 30 ); // third parameter is argument to called function 'func'
    
    function func(param){
       console.log(param);
    }
    

    // Anywhere you've access to timer declared above call clearInterval

    $('.htmlelement').click( function(){  // any event you want
    
           clearInterval(timer);// Stops or does the work
    });
    
    0 讨论(0)
  • 2020-11-21 05:49

    I guess the following code will help:

    var refreshIntervalId = setInterval(fname, 10000);
    
    clearInterval(refreshIntervalId);
    

    You did the code 100% correct... So... What's the problem? Or it's a tutorial...

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

    Use setTimeOut to stop the interval after some time.

    var interVal = setInterval(function(){console.log("Running")  }, 1000);
     setTimeout(function (argument) {
        clearInterval(interVal);
     },10000);
    
    0 讨论(0)
  • 2020-11-21 05:54

    This is how I used clearInterval() method to stop the timer after 10 seconds.

    function startCountDown() {
      var countdownNumberEl = document.getElementById('countdown-number');
      var countdown = 10;
      const interval = setInterval(() => {
        countdown = --countdown <= 0 ? 10 : countdown;
        countdownNumberEl.textContent = countdown;
        if (countdown == 1) {
          clearInterval(interval);
        }
      }, 1000)
    }
    <head>
      <body>
        <button id="countdown-number" onclick="startCountDown();">Show Time </button>
      </body>
    </head>

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

    setInterval() returns an interval ID, which you can pass to clearInterval():

    var refreshIntervalId = setInterval(fname, 10000);
    
    /* later */
    clearInterval(refreshIntervalId);
    

    See the docs for setInterval() and clearInterval().

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