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
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

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!