How can I make a program wait for a variable change in javascript?

Thanasis Petsas picture Thanasis Petsas · Sep 3, 2010 · Viewed 123.1k times · Source

I want to force a JavaScript program to wait in some particular points of its execution until a variable has changed. Is there a way to do it? I have already found an extension that is called "narrative JavaScript" that force the program to wait until an event to happen. Is there a way to create a new event, a "variable change event" for example that behaves like onclick event..

Answer

aularon picture aularon · Sep 3, 2010

Edit 2018: Please look into Object getters and setters and Proxies. Old answer below:


a quick and easy solution goes like this:

var something=999;
var something_cachedValue=something;

function doStuff() {
    if(something===something_cachedValue) {//we want it to match
        setTimeout(doStuff, 50);//wait 50 millisecnds then recheck
        return;
    }
    something_cachedValue=something;
    //real action
}

doStuff();