如何将setTimeout与递归一起使用以等待在JavaScript中定义变量?

时间:2017-02-06 23:39:10

标签: javascript jquery

我想等到 storage.get('session')!=null ,然后执行 callback

我遇到的问题是我的递归setTimeout方法是以指数方式运行,而不是检查变量是否每秒都定义。

结果是waitForElement每秒执行数千次,我不想要..我希望它每1秒执行一次,直到storage.get('session')!=null

waitForElement(function(){
    console.log("DONE!");
});

function waitForElement(callback){
    if(storage.get('session')!=null)
    {
        console.log("session exists now");
        if(typeof callback=="function")
        {
            callback();
        }
    }
    else
    {
        console.log("session still does not exist. Checking again in 1 second");

        //ISSUE: THIS RUNS IMMEDIATELY AND FOREVER!
        setTimeout(waitForElement(function(cb){
                if(typeof cb == "function"){
                    cb();
                }
        }), 1000);
    }
}

3 个答案:

答案 0 :(得分:5)

你根本不应该使用超时 - Promise是目前这种异步处理的首选模型,例如。

function login() {
    return new Promise((resolve, reject) => {
        // do something that creates the session
        if (successful) {
            resolve();
        } else {
            reject();
        }
    })
}

// promise that will eventually be resolve when the user logs in
var loggedIn = login();

// multiple (potentially parallel) actions
loggedIn.then(doSomething);
loggedIn.then(doSomethingElse);

// serial actions
loggedIn.then(doFirstThing).then(doSecondThing);

答案 1 :(得分:0)

这是因为您在设置超时后立即调用函数waitForElement。试试这个

var callback = function(cb){
    if(typeof cb == "function"){
        cb();
    }
}

setTimeout(waitForElement.bind(this, callback), 1000);

答案 2 :(得分:0)

您正在立即调用waitForElement。你需要传递一个函数引用,它基本上是一个没有"()"的函数名。鉴于你的功能没有"这个"没有必要担心这种情况的背景。

setTimeout(function() {
    waitForElement(function(cb){
        if(typeof cb == "function"){
            cb();
        }
    });
}, 1000);

还需要注意的是,你永远不会将任何内容传递给回调函数。