switz
switz

Reputation: 25188

clearInterval(); then call interval again

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?

Upvotes: 1

Views: 5722

Answers (4)

Jacob Relkin
Jacob Relkin

Reputation: 163228

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

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

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.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754575

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

Upvotes: 4

Jon Onstott
Jon Onstott

Reputation: 13727

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

Upvotes: 0

Related Questions