9

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kesantielu Dasefern
  • 266
  • 1
  • 3
  • 12
  • Variables are passed by value, not by reference, so you're just passing the current, undefined value in your `setTimeout`. – Barmar Dec 26 '16 at 08:41
  • 2
    You're passing the value of `a`, which will always be `undefined` – haim770 Dec 26 '16 at 08:41

2 Answers2

14

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.

Community
  • 1
  • 1
Scimonster
  • 32,893
  • 9
  • 77
  • 89
0
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)
Anil Talla
  • 709
  • 5
  • 19