想要每分钟运行一次javascript函数,但最多3次

mrb*_*lah 16 javascript ajax jquery

我有一个ajax javascript方法从页面中提取数据等.

我希望这个过程以定时间隔运行,比如每分钟.但我不希望它永远循环,所以最多3次.

实现这个的最佳方法是什么?

SLa*_*aks 41

像这样:

var runCount = 0;    
function timerMethod() {
    runCount++;
    if(runCount > 3) clearInterval(timerId);

    //...
}

var timerId = setInterval(timerMethod, 60000);    //60,000 milliseconds
Run Code Online (Sandbox Code Playgroud)

  • +1 - 这是更好的解决方案.使用`setInterval()`你可以避免不断地反复调用`setTimeout()`,而`foo()`的循环时间稍微快一些,因为你不必等待`foo()`来处理所有事情之前设置下一个电话. (3认同)

Tom*_*lak 12

基于闭包的解决方案,使用setInterval()clearInterval():

// define a generic repeater
var repeater = function(func, times, interval) {
  var ID = window.setInterval( function(times) {
    return function() {
      if (--times <= 0) window.clearInterval(ID);
      func();
    }
  }(times), interval);
};

// call the repeater with a function as the argument
repeater(function() {
  alert("stuff happens!");
}, 3, 60000);
Run Code Online (Sandbox Code Playgroud)

编辑:另一种表达相同的方式,使用setTimeout():

var repeater = function(func, times, interval) {
  window.setTimeout( function(times) {
    return function() {
      if (--times > 0) window.setTimeout(arguments.callee, interval);
      func();
    }
  }(times), interval);
};

repeater(function() {
  alert("stuff happens!");
}, 3, 2000);
Run Code Online (Sandbox Code Playgroud)

也许后者更容易理解.

在该setTimeout()版本中,您可以确保下一次迭代仅在前一次迭代完成才会发生.你只需将func()线以上setTimeout()线.