Stop setInterval call in JavaScript

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 user to be able to stop the repeated refresh of data.


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() .


如果将setInterval的返回值设置为变量,则可以使用clearInterval将其停止。

var myTimer = setInterval(...);
clearInterval(myTimer);

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.

链接地址: http://www.djcxy.com/p/51606.html

上一篇: setTimeout或setInterval?

下一篇: 在JavaScript中停止setInterval调用