clearInterval();然后再次调用间隔

时间:2010-12-08 00:48:25

标签: javascript

我有一个setInterval函数

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

我想稍后再调用setInterval,最好的方法是什么?

4 个答案:

答案 0 :(得分:4)

尝试将代码分解为间隔和设置的存储。

var auto_refresh = "";

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

添加了一个jsfiddle示例,用于演示启动和停止间隔

答案 1 :(得分:1)

clearInterval接受您要清除的计时器的引用,您需要将其传递给它:

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

答案 2 :(得分:1)

这可能就是你要找的东西

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.

答案 3 :(得分:0)

也许您只想使用setTimeout(),以便拥有您正在寻找的控件?