开发者

How to Clear Interval when Using Set Interval in jQuery?

开发者 https://www.devze.com 2023-04-02 11:44 出处:网络
I have a jquery plugin that autofreshes the page every 5 mins. (function($) { $.fn.refreshPage = function() {

I have a jquery plugin that autofreshes the page every 5 mins.

(function($) {
  $.fn.refreshPage = function() {

    setInterval(function() {
      function x();
    }, 300);
  };
})(jQuery);

but the problem is that I want it to reset the timer when a certain function runs, I've read about clearInterval, but I'm not sure how to implement that here. To be more specific, I want function x to clear the interval everytime it runs.

Follow up question:

How do I call clearInterval on a function on another file given the current structure of my plugin? Sorry noob here. Thanks!

Any help would be appreciated. Thanks in advance!

UPDATE:

My plugin now looks like this

(function($) {
  var refresh_timer;
  $.fn.refreshPage = function() {

    refresh_timer = setInte开发者_运维技巧rval(function() {
      function x();
    }, 300);
  };
  $.fn.reFreshPage.resetTimer = function() {
    clearInterval(refresh_timer);
})(jQuery);

And I call:

$.fn.reFreshPage.resetTimer

to reset the intervals, but the problem is that it breaks the setInterval and no longer refreshes the page after the timer has been reset. Am I missing something here?


You just have to remember the return value from the original call to setInterval and you can then pass that to clearInterval in order to stop the timer.

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

Sometimes, when you want more control, it's easier to not use setInterval(), but to use setTimeout() and just repeatedly call setTimeout() on each successive timer until you want it to stop. This technique also makes it easier to vary the timer interval if desired.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号