setInterval/setTimeout を使用して、関数が FINISH を実行してからしばらく待ってから再度実行し、FINISH してから待機するなどを確認するにはどうすればよいですか。ありがとう。
2 に答える
5
これは、チェーン化された一連の の古典的な使用例ですsetTimeout
。
setTimeout(foo, yourInterval);
function foo() {
// ...do the work...
// Schedule the next call
setTimeout(foo, yourInterval);
}
関数への1 回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
急速に混沌とします。
于 2013-01-27T00:10:50.533 に答える
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
);
于 2013-01-27T00:25:02.223 に答える