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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With