JavaScript waitFor Polling

As extra of the JavaScript builders write turns into asynchronous, it is solely pure to want to attend for situations to be met. That is very true in a world with asynchronous testing of situations which do not present an express await. I’ve written about waitForever, waitForTime, and JavaScript Polling up to now, however I needed to have a extra fashionable method of awaiting a given state. Let’s take a look at this tremendous helpful waitFor perform!

waitFor is an async perform that permits builders to offer a situation perform, polling interval (in milliseconds), and optionally available timeout (in milliseconds).

// Polls each 50 milliseconds for a given situation
const waitFor = async (situation, pollInterval = 50, timeoutAfter) => {
  // Observe the beginning time for timeout functions
  const startTime =;

  whereas (true) {
    // Verify for timeout, bail if an excessive amount of time handed
    if(typeof(timeoutAfter) === 'quantity' && > startTime + timeoutAfter) {
      throw 'Situation not met earlier than timeout';

    // Verify for conditon instantly
    const consequence = await situation();

    // If the situation is met...
    if(consequence) {
      // Return the consequence....
      return consequence;

    // In any other case wait and examine after pollInterval
    await new Promise(r => setTimeout(r, pollInterval));

Utilizing this perform is so simple as simply offering a situation perform:

await waitFor(() => doc.physique.classList.has('loaded'));

Timing out the interval and timeout can also be easy:

await waitFor(
  () => doc.physique.classList.has('loaded'),
  // Checks each 100 milliseconds
  // Throws if the "loaded" class is not on the physique after 1 second

In an excellent world, builders would all the time have a deal with on the Promise that may very well be await‘d or then‘d. In apply, nonetheless, that is not all the time the case, particularly in a testing atmosphere. Having the ability to await a situation in any atmosphere is an absolute should, so preserve this snippet in your toolbox!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button