JavaScript waitFor Polling

By  on  

As more of the JavaScript developers write becomes asynchronous, it's only natural to need to wait for conditions to be met. This is especially true in a world with asynchronous testing of conditions which don't provide an explicit await. I've written about waitForever, waitForTime, and JavaScript Polling in the past, but I wanted to have a more modern way of awaiting a given state. Let's have a look at this super useful waitFor function!

waitFor is an async function that allows developers to provide a condition function, polling interval (in milliseconds), and optional timeout (in milliseconds).

// Polls every 50 milliseconds for a given condition
const waitFor = async (condition, pollInterval = 50, timeoutAfter) => {
  // Track the start time for timeout purposes
  const startTime = Date.now();

  while (true) {
    // Check for timeout, bail if too much time passed
    if(typeof(timeoutAfter) === 'number' && Date.now() > startTime + timeoutAfter) {
      throw 'Condition not met before timeout';
    }

    // Check for conditon immediately
    const result = await condition();

    // If the condition is met...
    if(result) {
      // Return the result....
      return result;
    }

    // Otherwise wait and check after pollInterval
    await new Promise(r => setTimeout(r, pollInterval));
  }
};

Using this function is as simple as just providing a condition function:

await waitFor(() => document.body.classList.has('loaded'));

Timing out the interval and timeout is also simple:

await waitFor(
  () => document.body.classList.has('loaded'),
  // Checks every 100 milliseconds
  100,
  // Throws if the "loaded" class isn't on the body after 1 second
  10000
);

In an ideal world, developers would always have a handle on the Promise that could be await'd or then'd. In practice, however, that isn't always the case, especially in a testing environment. Being able to await a condition in any environment is an absolute must, so keep this snippet in your toolbox!

Recent Features

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

Incredible Demos

  • By
    Prevent Page Zooming in Mobile Browsers

    Ever since I got my iPhone, I've been more agreeable in going places that my fiancee wants to go. It's not because I have any interest in checking out women's shoes, looking at flowers, or that type of stuff -- it's because my iPhone lets...

  • By
    Reverse Element Order with CSS Flexbox

    CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible.  Semantics...

Discussion

  1. Who knew asynchronous programming could be this elegant? This waitFor tutorial is a game-changer for smoother code execution. Thanks for sharing, David Walsh!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!