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 = setInterval(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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top