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)
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()
线.
归档时间: |
|
查看次数: |
25011 次 |
最近记录: |