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..
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Edit 2018: Please look into Object getters and setters and Proxies. Old answer below:
a quick and easy solution goes like this:
JavaScript interpreters are single threaded, so a variable can never change, when the code is waiting in some other code that does not change the variable.
In my opinion it would be the best solution to wrap the variable in some kind of object that has a getter and setter function. You can then register a callback function in the object that is called when the setter function of the object is called. You can then use the getter function in the callback to retrieve the current value:
This could be easily used like this:
No you would have to create your own solution. Like using the Observer design pattern or something.
If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!
Mike
You can use properties:
Object.defineProperty MDN documentation
Example:
I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:
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:
Handler
function(){alert("Value changed!");}
will be called (if you look at the code) whenSetValue()
is called.You can get value like so:
You can set value like so:
And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/