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

The question was posted long time ago, many answers pool the target periodically and produces unnecessary waste of resources if the target is unchanged. In addition, most answers do not block the program while waiting for changes as required by the original post.

We can now apply a solution that is purely event-driven.

The solution uses onClick event to deliver event triggered by value change.

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to wait

How to make the script wait/sleep in a simple way in unity How do I make a delay in Java? Wait some seconds without blocking UI execution Protractor : How to wait for page complete after click a button? How to wait until an element is present in Selenium? Javascript sleep/delay/wait function How to wait till the response comes from the $http request, in angularjs? How to add a "sleep" or "wait" to my Lua Script? Concept behind putting wait(),notify() methods in Object class How can I wait for 10 second without locking application UI in android