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

前端 未结 10 1798
耶瑟儿~
耶瑟儿~ 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 04:05

    What worked for me (I looked all over the place and ended up using someone's jsfiddler / very slightly modifying it - worked nicely) was to set that variable to an object with a getter and setter, and the setter triggers the function that is waiting for variable change.

    var myVariableImWaitingOn = function (methodNameToTriggerWhenChanged){
        triggerVar = this;
        triggerVar.val = '';
        triggerVar.onChange = methodNameToTriggerWhenChanged;
        this.SetValue(value){
            if (value != 'undefined' && value != ''){
                triggerVar.val = value; //modify this according to what you're passing in -
                //like a loop if an array that's only available for a short time, etc
                triggerVar.onChange(); //could also pass the val to the waiting function here
                //or the waiting function can just call myVariableImWaitingOn.GetValue()
            }
        };
        this.GetValue(){
            return triggerVar.val();
        };
     };
    

提交回复
热议问题