2
我有以下代碼的多個實例。如何將條件傳遞給運行setTimout的函數
var start_time = new Date().getTime();
setTimeout(function timeout(){
var current_time = new Date().getTime();
if(some_condition){
// do stuff
}else if(start_time - current_time > 10000){
console.error("... request is timing out.");
}else{
setTimeout(timeout, 30);
}
}, 1);
我想它抽象成類似
globalLibrary = {
timeout : function(name, condition, callback, repeat){
if(typeof repeat !== "number")
repeat = 30;
setTimeout(function timeout(){
var current_time = new Date().getTime();
if(condition){
callback();
}else if(start_time - current_time > 10000){
console.error(name + " request is timing out.");
}else{
setTimeout(timeout, repeat);
}
}, 1);
}
}
// .... somewhere else (not in global scope.)
// There are vars here that are used in the condition and in the callback function.
// They will change due to processes happening elsewhere.
// eg ajax requests and iframe sendMessages being received.
globalLibrary.timeout(
"something",
condition,
function(){
// do stuff.
}
);
如何做到這一點,這樣的條件隨每次迭代重新運行? 該條件可能包括多個ands和ors。
(我不使用的setInterval由於時機微妙的差異。)
謝謝,那太好了。 – SystemicPlural 2012-02-24 10:13:01