Skip to content Skip to sidebar Skip to footer

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 u

Solution 1:

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;

Solution 2:

With Promises:

function getListNodes() {
  return new Promise(function check(resolve) {
    if (window.listNodes.length === 3) { return resolve(window.listNodes); }
    setTimeout(() => check(resolve), 500);
  });
}

socket.onopen = async function() {
  const listNodes = await getListNodes();
  // use listNodes normally
};

Within an async function, the await keyword will pause the function until the Promise it waits for is resolved (or rejected).

The Promise returned from getListNodes() will retry the lookup every 500 milliseconds, and resolve if it finds that the length is sufficient.

Take note that natively, async functions are only supported in Chrome and in Edge. You will need Babel + Babel polyfill to use them everywhere.


Post a Comment for "JavaScript: Pause A Function And Wait On A Global Variable"