zom*_*bat 199
你想要setInterval()
:
var intervalID = setInterval(function(){alert("Interval reached");}, 5000);
Run Code Online (Sandbox Code Playgroud)
setInterval()的第一个参数也可以是要计算的代码字符串.
您可以使用以下方法清除周期性函数
clearInterval(intervalID);
Run Code Online (Sandbox Code Playgroud)
Mat*_*ugh 36
请注意,setInterval()通常不是定期执行的最佳解决方案 - 它实际上取决于您实际定期调用的javascript.
例如.如果你使用周期为1000毫秒的setInterval()并在周期函数中进行ajax调用,有时需要2秒才能返回,你将在第一个响应返回之前再进行一次ajax调用.这通常是不合需要的.
许多库都有定期的方法来防止使用setInterval天真的陷阱,例如Nelson给出的Prototype示例.
要使用具有jQuery ajax调用的函数来实现更强大的定期执行,请考虑以下内容:
function myPeriodicMethod() {
$.ajax({
url: ...,
success: function(data) {
...
},
complete: function() {
// schedule the next request *only* when the current one is complete:
setTimeout(myPeriodicMethod, 1000);
}
});
}
// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用setTimeout但跟踪变量中的已用时间,然后动态设置每次调用的超时延迟,以尽可能接近所需的时间间隔执行函数,但绝不会比获得响应更快.
gna*_*arf 15
每个人都有一个setTimeout/setInterval解决方案.我认为重要的是要注意你可以将函数传递给setInterval,而不仅仅是字符串.它实际上可能有点"安全"传递真正的函数而不是字符串,这些字符串将被"唤醒"到那些函数.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Run Code Online (Sandbox Code Playgroud)
要么:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
Run Code Online (Sandbox Code Playgroud)
还是老问题了。我还需要一个定期的任务执行器并编写TaskTimer。当您需要以不同的时间间隔运行多个任务时,这也很有用。
// Timer with 1000ms (1 second) base interval resolution.
var timer = new TaskTimer(1000)
// Add task(s) based on tick intervals.
timer.addTask({
name: 'job1', // unique name of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback: function (task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
Run Code Online (Sandbox Code Playgroud)
TaskTimer
在浏览器和Node中均可使用。有关所有功能,请参阅文档。
归档时间: |
|
查看次数: |
89112 次 |
最近记录: |