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?
                        
JavaScript is pass by value, so when you pass
atowait, you just pass the valueundefined.You can try passing a function for the wait condition instead:
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.