3

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 :)

1
  • I tried with the function setTimeOut I showed in my answer how this can be accomplished with setTimeout. How did you do it? Commented Jan 7, 2017 at 16:55

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.