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
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    Duplicate the jQuery Homepage Tooltips Using Dojo

    The jQuery homepage has a pretty suave tooltip-like effect as seen below: Here's how to accomplish this same effect using Dojo. The XHTML The above HTML was taken directly from the jQuery homepage -- no changes. The CSS The above CSS has been slightly modified to match the CSS rules already...

  • By
    Fix Anchor URLs Using MooTools 1.2

    The administrative control panel I build for my customers features FCKEditor, a powerful WYSIWYG editor that allows the customer to add links, bold text, create ordered lists, and so on. I provide training and documentation to the customers but many times they simply forget to...

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!