Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting until a variable exists with typeof causes an infinite loop

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?

like image 572
Kesantielu Dasefern Avatar asked Dec 26 '16 08:12

Kesantielu Dasefern


1 Answers

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.

like image 166
Scimonster Avatar answered Oct 15 '22 09:10

Scimonster