JavaScript waitForTime

By  on  

I write a lot of tests for new features within Firefox DevTools. We have hundreds of "mochitests" which open the browser and perform synthetic actions like clicking, typing, and other user actions. I've previously written about waitForever which essentially halts following actions without locking the browser. Another utility I enjoy is waitForTime, an async JavaScript function that I can await to give breathing time between two tasks.

Whenever I want to wait a given amount of time between tasks, I employ this function:

function waitForTime(ms) {
  return new Promise(r => setTimeout(r, ms));
}

/* Usage */
await waitForTime(200);
// ...do other thing...
await waitForTime(200);
// ...do next thing ...

It's important to point out that most waitForTime calls don't appear in the final test, since arbitrary timeouts lead to intermittent test failures, but they are helpful in knowing where I need to add polling for some other condition!

Recent Features

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

Discussion

  1. Pavan

    I have this kind of a function in all my apps and I usually name is delay.

  2. Dubbya

    You don’t have to put “async” in front of the function?

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