使用setInterval / setTimeout,如何确保我的函数FINISH在等待一段时间后再执行,然后再执行,然后等待,等等。感谢。
答案 0 :(得分:5)
这是链式系列setTimeout
:
setTimeout(foo, yourInterval);
function foo() {
// ...do the work...
// Schedule the next call
setTimeout(foo, yourInterval);
}
由于setTimeout
仅调度对该函数的单个调用,因此在函数完成其工作后重新安排它(如果适用)。
与setInterval
不同,只要您从异步工作的回调中重新安排它,即使您的函数所做的工作是异步的,这也能正常工作。例如:
setTimeout(foo, yourInterval);
function foo() {
callSomethingAsynchronous(function() {
// ...we're in the async callback, do the work...
// ...and now schedule the next call
setTimeout(foo, yourInterval);
});
}
相反,如果你正在做异步,那么使用setInterval
会很快变得混乱。
答案 1 :(得分:0)
function execute_and_wait( repeated_function, time_delay ) {
var next_run = function () {
var complete_callback = function () {
next_run();
}
var killcode = setTimeout(
function () {
repeated_function(complete_callback);
},
time_delay
);
return killcode;
};
return next_run;
}
用法:
// Runs a function that prints hi every 2 seconds
// Kills it after 10 seconds
var ka = function (r) { alert('hi'); r(); };
var runka = execute_and_wait(ka,2000);
var killka = runka();
setTimeout(
function () {
clearTimeout(killka);
},
10000
);