Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Pause a function and wait on a global variable

There is a global variable window.listNodes that is an array. This variable is refreshed each 3 seconds and is filled sequentially.

Another function onOpen() is triggered by the user and needs to have the global variable window.listNodes containing 3 elements, not less. What I seek to do: if the global variable has not a .length equal to 3 then the program waits that the other part of the code fills window.listNodes and then begin again the function onOpen().

socket.onopen = function onOpen() {
        if (window.listNodes.length === 3) {
            // Do something
        } else {
            // Wait and when window.listNodes.length === 3:
            onOpen(); 
        }
    });
};

Is there an easy way to do it? I tried with the function setTimeOut() and with a generator function and the keyword yield but I failed.

Thank you for your precious help :)

like image 290
Bastian Nanchen Avatar asked Nov 29 '25 20:11

Bastian Nanchen


1 Answers

This could use setTimeout and a custom interval to wait, for example, 500ms, to do it:

function onOpen() {
        if (window.listNodes.length === 3) {
            // Do something
        } else {
            // Wait and when window.listNodes.length === 3:
            setTimeout(onOpen, 500);
        }
    });
};

socket.onopen = onOpen;
like image 174
Max Koretskyi Avatar answered Dec 01 '25 13:12

Max Koretskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!