如何将条件传递给运行setTimeout的函数

时间:2012-02-24 09:52:01

标签: javascript

我有以下代码的多个实例。

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。)

1 个答案:

答案 0 :(得分:2)

基本上,您需要lazy evaluation条件。通过创建nullary函数,可以在支持函数式编程的语言中轻松实现这一功能,该函数在需要值时进行评估。

globalLibrary = {
    timeout: function(name, condition, callback, repeat){
        if(typeof repeat !== "number")
            repeat = 30;

        setTimeout(function timeout(){
            var current_time = new Date().getTime();
            if ( condition() ) { // Note: 'condition' is called
                callback();
            } else if (start_time - current_time > 10000) {
                console.error(name + " request is timing out.");
            } else {
                setTimeout(timeout, repeat);
            }
        }, 1);
    }
}

globalLibrary.timeout(
    "something",
    function () {return condition},
    function(){
        // do stuff.
    }       
);