Javascript 执行一段时间后重复的函数的好模式是什么?
使用setInterval/setTimeout,我如何确保我的函数在等待一段时间之前完成执行,然后再次执行,完成,然后等待,依此类推。谢谢。这是链接系列Javascript 执行一段时间后重复的函数的好模式是什么?,javascript,settimeout,setinterval,Javascript,Settimeout,Setinterval,使用setInterval/setTimeout,我如何确保我的函数在等待一段时间之前完成执行,然后再次执行,完成,然后等待,依此类推。谢谢。这是链接系列设置超时的经典用例: setTimeout(foo, yourInterval); function foo() { // ...do the work... // Schedule the next call setTimeout(foo, yourInterval); } 由于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
会很快变得混乱。这是一系列setTimeout
的链式用例的经典用法:
setTimeout(foo, yourInterval);
function foo() {
// ...do the work...
// Schedule the next call
setTimeout(foo, yourInterval);
}
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;
}
由于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
会很快变得混乱
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
);
用法:
// 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
);
像XHR请求之类的异步函数?像XHR请求之类的异步函数?