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
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

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!