I have multiple instances of the following code.
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);
I want to abstract it to something like
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.
}
);
How do I do this so that the condition is rerun with each iteration?
The condition may include multiple ands and ors.
(I’m not using setInterval due to subtle differences in the timing.)
Basically, you want lazy evaluation of the condition. This is easy implemented in languages supporting functional programming by creating a nullary function, which is evaluated when the value is needed.