JavaScript sleep Function

By  on  

The infamous sleep, or delay, function within any language is much debated.  Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful.  I say that to each their own and one rule can never dictate anything in this industry.

Writing a sleep function is simple and made even more usable with JavaScript Promises:

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));

// Usage!
sleep(500).then(() => {
    // Do something after the sleep!

Without promises you'd need to pass a callback; with our beautiful promises we simply resolve after the setTimeout and use then with the result to execute the next step.  You'll also note that the demo above uses ES6 arrow functions.

Recent Features

  • By
    Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    HTML5’s placeholder Attribute

    HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the...

  • By
    Create a Context Menu with Dojo and Dijit

    Context menus, used in the right type of web application, can be invaluable.  They provide shortcut methods to different functionality within the application and, with just a right click, they are readily available.  Dojo's Dijit frameworks provides an easy way to create stylish, flexible context...


  1. Thomas BROYER

    This is not a “sleep” function, as it doesn’t block the current (main) thread, it’s more an “after” function; à la Golang Sleep vs. After:

    • Thomas BROYER

      (of course, reading from the channel in Golang would block, so not really an appropriate comparison either, but you get the idea: things can happen between the call to the function and the “callback” happens)

    • MaxArt

      Of course, nothing like the classic ‘sleep’ function exists in Javascript – and should never exist, actually. The only blocking thing in Javascript has been a sync AJAX request – a relic of the past.
      It’s just a way to introduce a similar concept, but still in Javascript’s way of coding.

  2. selvagsz

    With await, this would look even more sweet,

    await sleep(500);
    // do stuff
    • MaxArt

      Yes, I was thinking of the same thing. The only thing that bugs me is that every function that uses await should be declared async.
      (Actually, it’s the main complaint about async/await…)

  3. This signal callback function I always used my program, sleep await used in synchronus programe

  4. Tolis

    Make sure you clear the timeout when the Promise resolves.

  5. Not a big fan of this approach.

    Without async/await, wrapping a setTimeout call into a non-blocking Promise does not add any value but readability, not to mention that it prevents the timer from being canceled.

  6. I agree that this isn’t a solution for a possible sleep function.
    From my point of view it should stop the current process (but not the event handling) and continue (within the same scope when it was called) afterwards.

    Thus, you may call it in a function without the need to split the function into two, which is necessary using the approach above.

    And when already talking about a sleep function, a processMessages() function, similar as in Delphi/Lazarus (Application.processMessages()) is needed too… :)

  7. Kay

    Not everyone likes or knows (like me) the magic of arrow functions. Here is the “same” code without =>

    function sleepAsync(time) {
      //return new Promise((resolve) => setTimeout(resolve, time));
        var p = new Promise();
        setTimeout(function() { p.resolve(); }, time);
        return p.promise();  
  8. Kay

    Ah, and this is usage without arrow function for both:

    // Usage!
        // Do something after the sleep!
  9. Vitaliy

    If you also need to clear promised timeout (like setTimeout does), consider this package:

    import Timeout from 'await-timeout';
    async function foo() {
      const timeout = new Timeout();
      try {
        const mainPromise = fetch('');
        const timerPromise = timeout.set(1000, 'Rejected by timeout');
        await Promise.race([mainPromise, timerPromise]);
      } catch (e) {
      } finally {

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