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

I want to make the JavaScript program wait at some points in its execution until the variable changes. Is there any way to do this? I already found an extension called "descriptive JavaScript" that makes the program wait for the event to happen. Is there a way to create a new event, such as a variable event, which behaves like an onclick event.

+56
javascript variables wait
Sep 03 '10 at 12:56
source share
9 answers

Edit 2018: Please take a look at getterters and setters and Proxies Objects . Old answer below:




A quick and easy solution looks 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(); 
+84
Sep 03 '10 at 13:00
source share

JavaScript interpreters are single-threaded, so a variable can never change when the code expects in some other code that does not change the variable.

In my opinion, this would be the best solution for transferring a variable to some object that has a getter and setter function. Then you can register the callback function in the object, which is called when the setter function of the object is called. Then you can use the getter function in the callback to get the current value:

 function Wrapper(callback) { var value; this.set = function(v) { value = v; callback(this); } this.get = function() { return value; } } 

This can be easily used as follows:

 <html> <head> <script type="text/javascript" src="wrapper.js"></script> <script type="text/javascript"> function callback(wrapper) { alert("Value is now: " + wrapper.get()); } wrapper = new Wrapper(callback); </script> </head> <body> <input type="text" onchange="wrapper.set(this.value)"/> </body> </html> 
+19
03 Sep '10 at 13:39
source share

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

 ​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 contain the value that you want to control, as well as a function that will be called when the value changes. For example, if you want to receive a warning when a value changes, and the initial value is 10, you should write the code as follows:

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

The function(){alert("Value changed!");} handler function(){alert("Value changed!");} Will be called (if you look at the code) when SetValue() called.

You can get the value like this:

 alert(myVar.GetValue()); 

You can set the value as follows:

 myVar.SetValue(12); 

And immediately after that, a warning appears on the screen. See how it works: http://jsfiddle.net/cDJsB/

+5
03 Sep '10 at 13:24
source share

You can use the properties :

MDD Object.defineProperty Documentation

Example:

 function def(varName, onChange) { var _value; Object.defineProperty(this, varName, { get: function() { return _value; }, set: function(value) { if (onChange) onChange(_value, value); _value = value; } }); return this[varName]; } def('myVar', function (oldValue, newValue) { alert('Old value: ' + oldValue + '\nNew value: ' + newValue); }); myVar = 1; // alert: Old value: undefined | New value: 1 myVar = 2; // alert: Old value: 1 | New value: 2 
+1
Nov 29 '14 at 15:13
source share

The question was published a long time ago, many answers periodically combine goals and lead to unnecessary waste of resources if the goal does not change. In addition, most responses do not block the program while waiting for changes, as required by the original message.

Now we can apply a solution based solely on events.

The solution uses the onClick event to deliver the event caused by the value change.

The solution can be run in modern browsers that support Promise and async / await. If you are using Node.js, consider EventEmitter as the best solution.

 <!-- This div is the trick. --> <div id="trick" onclick="onTrickClick()" /> <!-- Someone else change the value you monitored. In this case, the person will click this button. --> <button onclick="changeValue()">Change value</button> <script> // targetObj.x is the value you want to monitor. const targetObj = { _x: 0, get x() { return this._x; }, set x(value) { this._x = value; // The following line tells your code targetObj.x has been changed. document.getElementById('trick').click(); } }; // Someone else click the button above and change targetObj.x. function changeValue() { targetObj.x = targetObj.x + 1; } // This is called by the trick div. We fill the details later. let onTrickClick = function () { }; // Use Promise to help you "wait". This function is called in your code. function waitForChange() { return new Promise(resolve => { onTrickClick = function () { resolve(); } }); } // Your main code (must be in an async function). (async () => { while (true) { // The loop is not for pooling. It receives the change event passively. await waitForChange(); // Wait until targetObj.x has been changed. alert(targetObj.x); // Show the dialog only when targetObj.x is changed. await new Promise(resolve => setTimeout(resolve, 0)); // Making the dialog to show properly. You will not need this line in your code. } })(); </script> 
+1
Mar 14 '19 at 14:31
source share

Super outdated, but definitely good ways to accommodate this. Just wrote this for the project and decided that I would share. Like some others, they are diverse in style.

 var ObjectListener = function(prop, value) { if (value === undefined) value = null; var obj = {}; obj.internal = value; obj.watcher = (function(x) {}); obj.emit = function(fn) { obj.watch = fn; }; var setter = {}; setter.enumerable = true; setter.configurable = true; setter.set = function(x) { obj.internal = x; obj.watcher(x); }; var getter = {}; getter.enumerable = true; getter.configurable = true; getter.get = function() { return obj.internal; }; return (obj, Object.defineProperty(obj, prop, setter), Object.defineProperty(obj, prop, getter), obj.emit, obj); }; user._licenseXYZ = ObjectListener(testProp); user._licenseXYZ.emit(testLog); function testLog() { return function() { return console.log([ 'user._licenseXYZ.testProp was updated to ', value ].join(''); }; } user._licenseXYZ.testProp = 123; 
0
Jun 07 '19 at 7:18
source share

JavaScript is one of the worst programming and scripting languages!

"Wait" seems impossible in JavaScript! (Yes, as in real life, sometimes waiting is the best option!)

I tried the while loop and Recursion (the function calls itself several times, yet ...), but JavaScript still refuses to work! (This is unbelievable, but anyway, see the codes below :)

while loop:

 <!DOCTYPE html> <script> var Continue = "no"; setTimeout(function(){Continue = "yes";}, 5000); //after 5 seconds, "Continue" is changed to "yes" while(Continue === 'no'){}; //"while" loop will stop when "Continue" is changed to "yes" 5 seconds later //the problem here is that "while" loop prevents the "setTimeout()" to change "Continue" to "yes" 5 seconds later //worse, the "while" loop will freeze the entire browser for a brief time until you click the "stop" script execution button </script> 

Recursion:

 <!DOCTYPE html> 1234 <script> function Wait_If(v,c){ if (window[v] === c){Wait_If(v,c)}; }; Continue_Code = "no" setTimeout(function(){Continue_Code = "yes";}, 5000); //after 5 seconds, "Continue_Code" is changed to "yes" Wait_If('Continue_Code', 'no'); //the problem here, the javascript console trows the "too much recursion" error, because "Wait_If()" function calls itself repeatedly! document.write('<br>5678'); //this line will not be executed because of the "too much recursion" error above! </script> 
0
Jun 16 '19 at 17:16
source share

Alternatively, you can create a function that performs tasks based on the value of its “static” variables, for example below:

enter image description here

 <!DOCTYPE html> <div id="Time_Box"> Time </div> <button type="button" onclick='Update_Time("on")'>Update Time On</button> <button type="button" onclick='Update_Time("off")'>Update Time Off</button> <script> var Update_Time = (function () { //_____________________________________________________________ var Static = []; //"var" declares "Static" variable as static object in this function return function (Option) { var Local = []; //"var" declares "Local" variable as local object in this function if (typeof Option === 'string'){Static.Update = Option}; if (Static.Update === "on"){ document.getElementById("Time_Box").innerText = Date(); setTimeout(function(){Update_Time()}, 1000); //update every 1 seconds }; }; })(); Update_Time('on'); //turns on time update </script> 
0
Jun 16 '19 at 20:15
source share

No, you would have to create your own solution. Like using an Observer design pattern or something like that.

If you do not have control over the variable or who uses it, I am afraid that you are doomed. EDIT: Or use the Skilldrick solution!

Mike

-one
Sep 03 '10 at 13:00
source share



All Articles