Kayvar Kayvar - 4 years ago 117
Javascript Question

How do I use setTimeout with recursion to wait for a variable to be defined in JavaScript?

I want to wait until

storage.get('session')!=null
, then execute the
callback
.


The problem I'm having is that my recursive
setTimeout
method is running exponentially
instead of checking if the variable is defined every second.

The result is waitForElement being executed thousands of times per second which I do not want.. I want it to execute once every 1 second until
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);
}
}

Answer Source

You shouldn't be using timeouts at all - Promises are the preferred model for this sort of asynchronous handling these days, e.g.

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download