Waiting until a variable exists with typeof causes an infinite loop

2.3k views Asked by At

I need a function that waits until a variable comes into existence.

function wait(variable, callback) {
    if (typeof variable !== "undefined")
        callback();
    else
        setTimeout(function () {
            wait(variable, callback);
        }, 0)
}

Calling this function with the example code below causes an infinite loop.

var a;
wait(a, function(){console.log('success')});
setTimeout(function(){a=1}, 1000)

Why?

2

There are 2 answers

3
Scimonster On BEST ANSWER

JavaScript is pass by value, so when you pass a to wait, you just pass the value undefined.

You can try passing a function for the wait condition instead:

var a;
console.log('started');
wait(function(){return a}, function(){console.log('success')});
setTimeout(function(){a=1}, 1000)

function wait(condition, callback) {
    if (typeof condition() !== "undefined") {
        callback();
    } else {
        setTimeout(function () {
            wait(condition, callback);
        }, 0)
    }
}

You could also extend this method to wait for more than just the variable existing, but for when it has a certain value or something.

If you use NPM and promises, there's a library that does this already: wait-until-promise. There may be others that use classical callbacks as well.

0
Anil Talla On
var a ;
function wait(callback) {
if (typeof a !== "undefined") callback();
else setTimeout(function () {
        wait(callback);
    }, 0)
}
wait(function(){console.log('success')});
setTimeout(function(){a=1},1000)