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

前端 未结 10 1808
耶瑟儿~
耶瑟儿~ 2020-12-01 03:23

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 extens

10条回答
  •  孤街浪徒
    2020-12-01 03:51

    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();
    

提交回复
热议问题