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

前端 未结 10 1796
耶瑟儿~
耶瑟儿~ 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:00

    I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:

    ​function Variable(initVal, onChange)
    {
        this.val = initVal;          //Value to be stored in this object
        this.onChange = onChange;    //OnChange handler
    
        //This method returns stored value
        this.GetValue = function()  
        {
            return this.val;
        }
    
        //This method changes the value and calls the given handler       
        this.SetValue = function(value)
        {
            this.val = value;
            this.onChange();
        }
    
    
    }
    

    And then you can make an object out of it that will hold value that you want to monitor, and also a function that will be called when the value gets changed. For example, if you want to be alerted when the value changes, and initial value is 10, you would write code like this:

    var myVar = new Variable(10, function(){alert("Value changed!");});
    

    Handler function(){alert("Value changed!");} will be called (if you look at the code) when SetValue() is called.

    You can get value like so:

    alert(myVar.GetValue());
    

    You can set value like so:

    myVar.SetValue(12);
    

    And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/

提交回复
热议问题