clearInterval(); then call interval again

Asked by At

I have a setInterval function

var auto_refresh = setInterval(function () {
  if ($('#addNewJuicebox:visible')) {
    clearInterval();
  }
  //rest of function
}, 8000); // refresh every 5000 milliseconds

I want to call the setInterval later again, what's the best way to do that?

4 Answers

4
JaredPar On Best Solutions

Try breaking your code up into the storage of the interval and the setting.

var auto_refresh = "";

function startRefresh() {
  if (auto_refresh != "") {
    // already set
    return;
  }
  auto_refresh = setInterval(function() {
    if ($('#addNewJuicebox:visible')) { 
      clearInterval(auto_refresh); 
      auto_refresh = "";
    }
  }, 8000);
}

Added a jsfiddle example for demonstrating starting and stopping an interval

0
Jon Onstott On

Maybe you just want to use setTimeout() instead, so that you have the control you're looking for?

1
Jacob Relkin On

clearInterval takes in a reference to the timer that you want to clear, you need to pass that in to it:

var auto_refresh = null;
var refresh = function () {
    if ($('#addNewJuicebox').is(':visible')) {
        clearInterval(auto_refresh);
        auto_refresh = null;
    }
};
var start_refreshing = function() {
    if(auto_refresh != null) return;
    auto_refresh = setInterval(refresh, 8000); 
};
start_refreshing();
1
Juan Mendes On

This may be what you're looking for

Function TaskRunner(run, interval) {
  this._taskId = null;
  this._run = run;
  this._interval = interval
}

TaskRunner.prototype.start = function(){
  if (this._taskId) {
    return; // Already running
  }
  this._taskId = setInterval(this._taskId, this._interval);
}

TaskRunner.prototype.stop = function(){
  if (!this._taskId) {
    return; // Not running
  }
  clearInterval(this._taskId);
  this._taskId = null;
}


var task = new TaskRunner(
  function(){
    if ($('#addNewJuicebox:visible')) {
      task.stop();
    }
   // Do the update     
  }, 5000);

Now you can call `task.start()` from anywhere in your code to restart it.