3528

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

This is not a duplicate of Sleep in JavaScript - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

10
  • 261
    This is a horrible solution - you're going to be chewing up processing cycles while doing nothing.
    – 17 of 26
    Jun 4, 2009 at 14:47
  • 20
    The only purpose for a sleep is polling or waiting for a callback - setInterval and setTimeout do both better than this.
    – annakata
    Jun 4, 2009 at 14:50
  • 1
    Probably you can do what you want with continuation passing style in JavaScript. Take a look at this article. May 15, 2015 at 8:02
  • 53
    It is amazing to see people saying no without understanding what the OP wants. There are cases that you want a real sleep. I am now needing a real sleep to test the browsers behaviour of posting and receiving message between the top window and the iframe. Keeping it busy with while seems the only way. Jun 6, 2020 at 4:18
  • 12
    @DevsloveZenUML and designers and developers of browser environment decided for the sake of users that you shall NOT have your wish because giving someone explicit ability to block entire page in async application is insane. Jan 13, 2022 at 12:30

91 Answers 91

9

You could do something like this. A sleep method that all functions can inherit:

Function.prototype.sleep = function(delay, ...args) {
    setTimeout(() => this(...args), delay)
}

console.log.sleep(2000, 'Hello, World!!')

2
  • 3
    My favorite so far
    – pasha
    Jun 17, 2020 at 12:13
  • 1
    This is the best solution! No busy-wait, and you can append it to any function to cause a delay before the execution of that function alone.
    – Akumaburn
    Jan 18 at 15:31
9

I suggest this method for former python developers

const sleep = (time) => {
   return new Promise((resolve) => setTimeout(resolve, Math.ceil(time * 1000)));
};

Usage:

await sleep(10) // for 10 seconds
8

You can't do a sleep like that in JavaScript, or, rather, you shouldn't. Running a sleep or a while loop will cause the user's browser to hang until the loop is done.

Use a timer, as specified in the link you referenced.

8

It can be done using Java's sleep method. I've tested it in Firefox and Internet Explorer and it doesn't lock the computer, chew up resources, or cause endless server hits. It seems like a clean solution to me.

First you have to get Java loaded up on the page and make its methods available. To do that, I did this:

<html>
<head>

<script type="text/javascript">

  function load() {
    var appletRef = document.getElementById("app");
    window.java = appletRef.Packages.java;
  } // endfunction

</script>

<body onLoad="load()">

<embed id="app" code="java.applet.Applet" type="application/x-java-applet" MAYSCRIPT="true" width="0" height="0" />

Then, all you have to do when you want a painless pause in your JavaScript code is:

java.lang.Thread.sleep(xxx)

Where xxx is time in milliseconds. In my case (by way of justification), this was part of back-end order fulfilment at a very small company and I needed to print an invoice that had to be loaded from the server. I did it by loading the invoice (as a webpage) into an iFrame and then printing the iFrame.

Of course, I had to wait until the page was fully loaded before I could print, so the JavaScript code had to pause. I accomplished this by having the invoice page (in the iFrame) change a hidden form field on the parent page with the onLoad event. And the code on the parent page to print the invoice looked like this (irrelevant parts cut for clarity):

var isReady = eval('document.batchForm.ready');
isReady.value = 0;

frames['rpc_frame'].location.href = url;

while (isReady.value == 0) {
  java.lang.Thread.sleep(250);
} // endwhile

window.frames['rpc_frame'].focus();
window.frames['rpc_frame'].print();

So the user pushes the button, the script loads the invoice page, waits, checking every quarter second to see if the invoice page is finished loading, and pops up the print dialog for the user to send it to the printer. QED.

2
  • 13
    Seems quite monstrous soulution when considering the simple thing author wanted to achieve.
    – xaralis
    Jan 22, 2013 at 16:17
  • 3
    This depends on Java Applets which is deprecated. May 12, 2016 at 13:22
8

If you're on Node.js, you can have a look at fibers – a native C extension to node, a kind of-multi-threading simulation.

It allows you to do a real sleep in a way which is blocking execution in a fiber, but it's non-blocking in the main thread and other fibers.

Here's an example fresh from their own readme:

// sleep.js

var Fiber = require('fibers');

function sleep(ms) {
    var fiber = Fiber.current;
    setTimeout(function() {
        fiber.run();
    }, ms);
    Fiber.yield();
}

Fiber(function() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);
}).run();
console.log('back in main');

– and the results are:

$ node sleep.js
wait... Fri Jan 21 2011 22:42:04 GMT+0900 (JST)
back in main
ok... Fri Jan 21 2011 22:42:05 GMT+0900 (JST)
7

For the specific case of wanting to space out a set of calls being executed by a loop, you can use something like the code below with prototype. Without prototype, you can substitute the delay function with setTimeout.

function itemHandler(item)
{
    alert(item);
}

var itemSet = ['a','b','c'];

// Each call to itemHandler will execute
// 1 second apart
for(var i=0; i<itemSet.length; i++)
{
    var secondsUntilExecution = i;
    itemHandler.delay(secondsUntilExecution, item)
}
0
7

One scenario where you might want a sleep() function rather than using setTimeout() is if you have a function responding to a user click that will ultimately end up opening a new i.e. popup window and you have initiated some processing that requires a short period to complete before the popup is displayed. Moving the open window into a closure means that it typically gets blocked by the browser.

7

An old question from 2009. Now in 2015 a new solution is possible with generators defined in ECMAScript 2015 AKA ES6. It was approved in June 2015, but it was implemented in Firefox and Chrome before. Now a sleep function can be made non-busy, non-blocking and nested inside loops and sub-functions without freezing the browser. Only pure JavaScript is needed - no libraries or frameworks.

The program below shows how sleep() and runSleepyTask() can be made. The sleep() function is only a yield statement. It is so simple that it is actually easier to write the yield statement directly in stead of calling sleep(), but then there would be no sleep-word :-) The yield returns a time value to the next() method inside wakeup() and waits. The actual "sleeping" is done in wakeup() using the good old setTimeout(). At callback the the next() method triggers the yield statement to continue, and the "magic" of yield is that all the local variables and the whole call-stack around it is still intact.

Functions that use sleep() or yield must be defined as generators. It is easily done by adding an asterisk to the keyword function*. To execute a generator is a bit trickier. When invoked with the keyword new the generator returns an object that has the next() method, but the body of the generator is not executed (the keyword new is optional and makes no difference). The next() method triggers execution of the generator body until it encounters a yield. The wrapper function runSleepyTask() starts up the ping-pong: next() waits for a yield, and yield waits a next().

Another way to invoke a generator is with keyword yield*, here it works like a simple function call, but it also includes the ability to yield back to next().

This is all demonstrated by the example drawTree(). It draws a tree with leaves on a rotating 3D scene. A tree is drawn as a trunk with 3 parts at the top in different directions. Each part is then drawn as another but smaller tree by calling drawTree() recursively after a short sleep. A very small tree is drawn as only a leaf.

Each leaf has its own life in a separate task started with runSleepyTask(). It is born, grows, sits, fades, falls and dies in growLeaf(). The speed is controlled with sleep(). This demonstrates how easy multitasking can be done.

function* sleep(milliseconds) {yield milliseconds};

function runSleepyTask(task) {
    (function wakeup() {
        var result = task.next();
        if (!result.done) setTimeout(wakeup, result.value);
    })()
}
//////////////// written by Ole Middelboe  /////////////////////////////

pen3D =setup3D();
var taskObject = new drawTree(pen3D.center, 5);
runSleepyTask(taskObject);

function* drawTree(root3D, size) {
    if (size < 2) runSleepyTask(new growLeaf(root3D))
    else {
        pen3D.drawTrunk(root3D, size);
        for (var p of [1, 3, 5]) {
            var part3D = new pen3D.Thing;
            root3D.add(part3D);
            part3D.move(size).turn(p).tilt(1-p/20);
            yield* sleep(50);
            yield* drawTree(part3D, (0.7+p/40)*size);
        }
    }
}

function* growLeaf(stem3D) {
    var leaf3D = pen3D.drawLeaf(stem3D);
    for (var s=0;s++<15;) {yield* sleep(100); leaf3D.scale.multiplyScalar(1.1)}
    yield* sleep( 1000 + 9000*Math.random() );
    for (var c=0;c++<30;) {yield* sleep(200); leaf3D.skin.color.setRGB(c/30, 1-c/40, 0)}
    for (var m=0;m++<90;) {yield* sleep( 50); leaf3D.turn(0.4).tilt(0.3).move(2)}
    leaf3D.visible = false;
}
///////////////////////////////////////////////////////////////////////

function setup3D() {
    var scene, camera, renderer, diretionalLight, pen3D;

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75,
        window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 15, 20);
    renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    directionalLight = new THREE.DirectionalLight(0xffffaa, 0.7);
    directionalLight.position.set(-1, 2, 1);
    scene.add(directionalLight);
    scene.add(new THREE.AmbientLight(0x9999ff));

    (function render() {
        requestAnimationFrame(render);
        // renderer.setSize( window.innerWidth, window.innerHeight );
        scene.rotateY(10/60/60);
        renderer.render(scene, camera);
    })();

    window.addEventListener(
        'resize',
        function(){
            renderer.setSize( window.innerWidth, window.innerHeight );
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
       },
       false
    );

    pen3D = {
        drawTrunk: function(root, size) {
            // root.skin = skin(0.5, 0.3, 0.2);
            root.add(new THREE.Mesh(new THREE.CylinderGeometry(size/12, size/10, size, 16),
                root.skin).translateY(size/2));
            root.add(new THREE.Mesh(new THREE.SphereGeometry(size/12, 16),
                root.skin).translateY(size));
            return root;
        },

        drawLeaf: function(stem) {
            stem.skin.color.setRGB(0, 1, 0);
            stem.add(new THREE.Mesh(new THREE.CylinderGeometry(0, 0.02, 0.6),
                stem.skin) .rotateX(0.3).translateY(0.3));
            stem.add(new THREE.Mesh(new THREE.CircleGeometry(0.2),
                stem.skin) .rotateX(0.3).translateY(0.4));
            return stem;
        },

        Thing: function() {
            THREE.Object3D.call(this);
            this.skin = new THREE.MeshLambertMaterial({
                color: new THREE.Color(0.5, 0.3, 0.2),
                vertexColors: THREE.FaceColors,
                side: THREE.DoubleSide
            })
        }
    };

    pen3D.Thing.prototype = Object.create(THREE.Object3D.prototype);
    pen3D.Thing.prototype.tilt = pen3D.Thing.prototype.rotateX;
    pen3D.Thing.prototype.turn = pen3D.Thing.prototype.rotateY;
    pen3D.Thing.prototype.move = pen3D.Thing.prototype.translateY;

    pen3D.center = new pen3D.Thing;
    scene.add(pen3D.center);

    return pen3D;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>

The 3D stuff is hidden inside setup3D() and is only included to make it less boring than console.log(). Angles are measured in radians by the way.

Tested to work in Firefox and Chrome. Not implemented in Internet Explore and iOS (iPads). Try to run it yourself.

After another pass of the answers I found, that Gabriel Ratener made a similar answer a year ago to What is the JavaScript version of sleep()?.

7

In the sleep method you can return any then-able object. And not necessarily a new promise.

Example:

const sleep = (t) =>  ({ then: (r) => setTimeout(r, t) })

const someMethod = async () => {

    console.log("hi");
    await sleep(5000)
    console.log("bye");
}

someMethod()

4

First of all - setTimeout and setInterval is what should be used, because of JavaScript's callback-ish nature. If you want to use sleep() it's the control flow or the architecture of your code that is incorrect.

Having said that I suppose I still can help with two implementation of a sleep.

1. Faking synchronous run off the top of my head:

// A module to do that //dual-license: MIT or WTF [you can use it anyhow and leave my nickname in a comment if you want to]
var _ = (function(){
  var queue = [];
  var play = function(){
    var go = queue.shift();
      if(go) {
        if(go.a) {
          go.f();
          play();
        }
        else
        {
          setTimeout(play, go.t);
        }
      }
  }
  return {
    go:function(f){
      queue.push({a:1, f:f});
    },
    sleep:function(t){
      queue.push({a:0, t:t});
    },
    playback:play
  }
})();

[making playback automatic should also be possible]

// Usage

_.go(function(){

  // Your code
  console.log('first');

});

_.sleep(5000);

_.go(function(){

  // Your code
  console.log('next');

});

// This triggers the simulation
_.playback();

2. Real synchronous run

I gave it a lot of thought one day and the only idea I had for a true sleep in JavaScript is technical.

A sleep function would have to be a synchronous Ajax call with a timeout set to the sleep value. That's all and the only way to have a real sleep().

0
4

Code taken from this link will not freeze the computer. But it works only in Firefox.

/**
 * Netscape compatible WaitForDelay function.
 * You can use it as an alternative to Thread.Sleep() in any major programming language
 * that support it while JavaScript it self doesn't have any built-in function to do such a thing.
 * parameters:
 * (Number) delay in millisecond
 */
function nsWaitForDelay(delay) {
    /**
     * Just uncomment this code if you're building an extension for Firefox.
     * Since Firefox 3, we'll have to ask for user permission to execute XPCOM objects.
     */
    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

    // Get the current thread.
    var thread = Components.classes["@mozilla.org/thread-manager;1"].getService(Components.interfaces.nsIThreadManager).currentThread;

    // Create an inner property to be used later as a notifier.
    this.delayed = true;

    /* Call JavaScript setTimeout function
      * to execute this.delayed = false
      * after it finishes.
      */
    setTimeout("this.delayed = false;", delay);

    /**
     * Keep looping until this.delayed = false
     */
    while (this.delayed) {
        /**
         * This code will not freeze your browser as it's documented in here:
         * https://developer.mozilla.org/en/Code_snippets/Threads#Waiting_for_a_background_task_to_complete
         */
        thread.processNextEvent(true);
    }
}
4

If you write a sleep function like this

var sleep = function(period, decision, callback){
    var interval = setInterval(function(){
        if (decision()) {
            interval = clearInterval(interval);
            callback();
        }
    }, period);
}

and you have an asynchronous function to call multiple times,

var xhr = function(url, callback){
    // Make an Ajax request
    // Call a callback when the request fulfils
}

And you set up your project like this:

var ready = false;

function xhr1(){
    xhr(url1, function(){ ready = true;});
}
function xhr2(){
    xhr(url2, function(){ ready = true; });
}
function xhr3(){
    xhr(url3, function(){ ready = true; });
}

Then you can do this:

xhr1();
sleep(100, function(){ return done; }, xhr2);
sleep(100, function(){ return done; }, xhr3);
sleep(100, function(){ return done; }, function(){
    // Do more
});

Instead of endless callback indentation like this:

xhr(url1, function(){
    xhr2(url2, function(){
        xhr3(url3, function(){
            // Do more
        });
    });
});
4

This is a blocking version of sleep. Found it easier to follow during testing activities where you need sequential execution. It can be called like sleep(2000) to sleep the thread for 2 seconds.

function sleep(ms) {
    const now = Date.now();
    const limit = now + ms;
    let execute = true;
    while (execute) {
        if (limit < Date.now()) {
            execute = false;
        }
    }
    return;
  }
3

I prefer this functional style one liner sleep function:

const sleep = (ms) => new Promise((res) => setTimeout(res, ms, ms));

// usage
async function main() {
  console.log("before");
  const t = await sleep(10_000); /* 10 sec */
  console.log("after " + t);
}
main();
1
  • 5
    This is not sleep funciton. If you call sleep function, it will not wait until time is lapsed, it will execute next instructions immediately.
    – Zeel Shah
    Feb 14, 2019 at 7:06
3

I needed a busy-wait for testing purposes. I didn't want to split the code as that would be a lot of work, so a simple for did it for me.

for (var i=0; i<1000000; i++){                  
    // Waiting
}

I didn't see any downside in doing this and it did the trick for me.

4
  • That might be compiled away. Jul 19, 2013 at 20:22
  • 1
    Please don't do it this way. This is a blocking sleep call, which means no other javascript can run while your code is hogging the JS thread. Oct 22, 2014 at 4:47
  • 7
    @SteveMidgley "no other javascript [being able to] run while your code is hogging the JS thread" seems to me to be exactly what the OP wants to do ¯_(ツ)_/¯ Mar 10, 2015 at 22:39
  • 2
    I just ran some tests and it appears even an empty loop will block the browser and CPU (not just JavaScript). And using for loops will almost always execute immediately, regardless of the max value for i, and even with complex math code placed inside. So unless you're only waiting for a few milliseconds, there still seems to be no way to sleep gracefully in JS.
    – Beejor
    Jun 14, 2015 at 22:03
3

In case you really need a sleep() just to test something. But be aware that it'll crash the browser most of the times while debugging - probably that's why you need it anyway. In production mode I'll comment out this function.

function pauseBrowser(millis) {
    var date = Date.now();
    var curDate = null;
    do {
        curDate = Date.now();
    } while (curDate-date < millis);
}

Don't use new Date() in the loop, unless you want to waste memory, processing power, battery and possibly the lifetime of your device.

2
  • 3
    Your code is virtually the same as the code in the question, which asks if there's a better way of doing this. Jan 9, 2015 at 22:26
  • "This" is relative to each one. The title of the question is: "What do I do if I want a JavaScript version of sleep()?" Use setTimeout or setInterval envolves a different reasoning, what may take more time, so is not always the choice, for instance for a fast debug test. Also, Date.now() is far more memory efficient than new Date() inside a loop, if I'm not wrong.
    – Rodrigo
    Jan 9, 2015 at 23:25
3

Naively, you can implement sleep() with a while loop same as the pausecomp function (this is basically the same):

const sleep = (seconds) => {
    const waitUntil = new Date().getTime() + seconds * 1000
    while(new Date().getTime() < waitUntil) {
        // do nothing
    }
}

And you can use the sleep() method like so:

const main = () => {
    const a = 1 + 3

    // Sleep 3 seconds before the next action
    sleep(3)
    const b = a + 4

    // Sleep 4 seconds before the next action
    sleep(4)
    const c = b + 5
}

main()

This is how I imagine you would use the sleep function, and is relatively straightforward to read. I borrowed from the other post Sleep in JavaScript - delay between actions to show how you may have been intending to use it.

Unfortunately, your computer will get warm and all work will be blocked. If running in a browser, the tab will grind to a halt and the user will be unable to interact with the page.

If you restructure your code to be asynchronous, then you can leverage setTimeout() as a sleep function same as the other post.

// define sleep using setTimeout
const sleep = (seconds, callback) => setTimeout(() => callback(), seconds * 1000)

const main = () => {
    const a = 1 + 3
    let b = undefined
    let c = undefined

    // Sleep 3 seconds before the next action
    sleep(3, () => {
        b = a + 4

        // Sleep 4 seconds before the next action
        sleep(4, () => {
            c = b + 5
        })
    })
}

main()

As you said, this isn't what you wanted. I modified the example from Sleep in JavaScript - delay between actions to show why this might be. As you add more actions, you will either need to pull your logic into separate functions or nest your code deeper and deeper (callback hell).

To solve "callback hell", we can define sleep using promises instead:

const sleep = (seconds) => new Promise((resolve => setTimeout(() => resolve(), seconds * 1000)))

const main = () => {
    const a = 1 + 3
    let b = undefined
    let c = undefined

    // Sleep 3 seconds before the next action
    return sleep(3)
        .then(() => {
            b = a + 4

            // Sleep 4 seconds before the next action
            return sleep(4)
        })
        .then(() => {
            c = b + 5
        })
}

main()

Promises can avoid the deep nesting, but still doesn't look like the regular synchronous code that we started with. We want to write code that looks synchronous, but doesn't have any of the downsides.

Let's rewrite our main method again using async/await:

const sleep = (seconds) => new Promise((resolve => setTimeout(() => resolve(), seconds * 1000)))

const main = async () => {
    const a = 1 + 3

    // Sleep 3 seconds before the next action
    await sleep(3)
    const b = a + 4

    // Sleep 4 seconds before the next action
    await sleep(4)
    const c = b + 5
}

main()

With async/await, we can call sleep() almost as if it was a synchronous, blocking function. This solves the problem you may have had with the callback solution from the other post and avoids issues with a long-running loop.

2

This will do you the trick.

var reloadAfter = 10; //seconds
var intervalId = setTimeout(function() {
    //code you want to execute after the time waiting
}, reloadAfter * 1000); // 60000 = 60 sec = 1 min
1
  • How is this different from previous answers? Jul 6, 2021 at 22:51
2

You can use a closure call setTimeout() with incrementally larger values.

var items = ['item1', 'item2', 'item3'];

function functionToExecute(item) {
  console.log('function executed for item: ' + item);
}

$.each(items, function (index, item) {
  var timeoutValue = index * 2000;
  setTimeout(function() {
    console.log('waited ' + timeoutValue + ' milliseconds');
    functionToExecute(item);
  }, timeoutValue);
});

Result:

waited 0 milliseconds
function executed for item: item1
waited 2000 milliseconds
function executed for item: item2
waited 4000 milliseconds
function executed for item: item3
4
  • 1
    This is a great way to limit the calls to an api before they get chance to cache. (Im my case I was sending a few duplicate postcodes to the google geocode api and caching the result, there were two problems. The loop would have executed so quick that the first api response would still be returning, and google geocode api has a rate limiter to would have just started rejecting requests).
    – chim
    Jan 4, 2017 at 15:56
  • tldr; you'll have to do something like tponthieux's answer when working in a loop context. (myArray.forEach or for(i=1; ...
    – chim
    Jan 4, 2017 at 15:56
  • 1
    We should get this answer voted up as it's useful and offers something different from the millions of other answers on this question.
    – chim
    Jan 4, 2017 at 15:59
  • Can you elaborate on "a closure call setTimeout()"? And what is the reason for "incrementally larger values"? Jul 6, 2021 at 16:43
2

If you like an advise to not lose performance. setTimeout is your expected sleep. However, if you want a syntax where code is "divided in middle" by sleep, we can do:

sleep = function(tm, fn){
   window.setTimeout(fn, tm);
}

Then, prepare functions as in the following:

var fnBeforeSleep = function(){

  // All code before sleep

}

var fnAfterSleep = function(){

  // All code after sleep

}

Then:

fnBeforeSleep();
sleep(2000, fnAfterSleep);

// Yep! Syntactically, it is very close to:

fnBeforeSleep();
sleep(2000);
fnAfterSleep();
2

Embrace the asynchronous nature of JavaScript!

All of the following will return immediately, but have a single place for putting code you want to run after something has happened.

The methods I've outlined here are all for different use cases and are roughly ordered in terms of their complexity.

The different things are as follows:

  • Waiting for some condition to become true
  • Waiting for a set of methods to finish (in any order) before calling a single callback
  • Running a series of asynchronous methods with shared state in a particular order before calling a callback

Wait

Waiting to see if some condition is true is useful where there isn't any accessible callback to tell you when something has finished executing.

This is a pretty basic implementation that assumes that the condition will become true at some point. With a few tweaks it could be expanded to be even more useful (for example, by setting a call limit). (I only wrote this one yesterday!)

function waitFor(predicate, successCallback) {
    setTimeout(function () {
        var result = predicate();
        if (result !== undefined)
            successCallback(result);
        else
            waitFor(predicate, successCallback);
    }, 100);
}

Calling code:

beforeEach(function (done) {
    selectListField('A field');

    waitFor(function () {
        var availableOptions = stores.scrapeStore(optionStore);
        if (availableOptions.length !== 0)
            return availableOptions;
    }, done);
});

Here I'm calling something which loads an Ext JS 'store' and waiting till the store contains something before continuing (the beforeEach is a Jasmine test framework thing).

Wait for several things to complete

I also needed to run a single callback after a load of different methods finished. You can do that like this:

createWaitRunner = function (completionCallback) {
    var callback = completionCallback;
    var completionRecord = [];
    var elements = 0;

    function maybeFinish() {
        var done = completionRecord.every(function (element) {
            return element === true
        });

        if (done)
            callback();
    }

    return {
        getNotifier: function (func) {
            func = func || function (){};

            var index = elements++;
            completionRecord[index] = false;

            return function () {
                func.applyTo(arguments);
                completionRecord[index] = true;
                maybeFinish();
            }
        }
    }
};

Calling code:

var waiter = createWaitRunner(done);

filterList.bindStore = waiter.getNotifier();
includeGrid.reconfigure = waiter.getNotifier(function (store) {
    includeStore = store;
});

excludeGrid.reconfigure = waiter.getNotifier(function (store) {
    excludeStore = store;
});

You either just wait for the notifications or can also wrap other functions which use the values passed to the function. When all the methods are called then done will be run.

Running asynchronous methods in order

I've used a different approach when I had a series of asynchronous methods to call in a row (again in tests). This is somewhat similar to something you can get in the Async library - series does about the same thing and I had a little read of that library first to see if it did what I wanted. I think mine has a nicer API for working with tests though (and it was fun to implement!).

// Provides a context for running asynchronous methods synchronously
// The context just provides a way of sharing bits of state
// Use 'run' to execute the methods.  These should be methods that take a callback and optionally the context as arguments
// Note the callback is provided first, so you have the option of just partially applying your function to the arguments you want
// instead of having to wrap even simple functions in another function

// When adding steps you can supply either just a function or a variable name and a function
// If you supply a variable name then the output of the function (which should be passed into the callback) will be written to the context
createSynchronisedRunner = function (doneFunction) {
    var context = {};

    var currentPosition = 0;
    var steps = [];

    // This is the loop. It is triggered again when each method finishes
    var runNext = function () {
        var step = steps[currentPosition];
        step.func.call(null,
                       function (output) {
                           step.outputHandler(output);
                           currentPosition++;

                           if (currentPosition === steps.length)
                               return;

                           runNext();
                       }, context);
    };

    var api = {};

    api.addStep = function (firstArg, secondArg) {
        var assignOutput;
        var func;

        // Overloads
        if (secondArg === undefined) {
            assignOutput = function () {
            };
            func = firstArg;
        }
        else {
            var propertyName = firstArg;
            assignOutput = function (output) {
                context[propertyName] = output;
            };
            func = secondArg;
        }

        steps.push({
            func: func,
            outputHandler: assignOutput
        });
    };

    api.run = function (completedAllCallback) {
        completedAllCallback = completedAllCallback || function(){};

        var lastStep = steps[steps.length - 1];
        var currentHandler = lastStep.outputHandler;
        lastStep.outputHandler = function (output) {
            currentHandler(output);
            completedAllCallback(context);
            doneFunction();
        };

        runNext();
    };

    // This is to support more flexible use where you use a done function in a different scope to initialisation
    // For example, the done of a test but create in a beforeEach
    api.setDoneCallback = function (done) {
        doneFunction = done;
    };

    return api;
};

Calling code:

beforeAll(function (done) {
    var runner = createSynchronisedRunner(done);
    runner.addStep('attachmentInformation', testEventService.getAttachmentCalled.partiallyApplyTo('cat eating lots of memory.jpg'));
    runner.addStep('attachment', getAttachment.partiallyApplyTo("cat eating lots of memory.jpg"));
    runner.addStep('noAttachment', getAttachment.partiallyApplyTo("somethingElse.jpg"));
    runner.run(function (context) {
        attachment = context.attachment;
        noAttachment = context.noAttachment;
    });
});

PartiallyApplyTo here is basically a renamed version of Douglas Crockford's implementation of Curry. A lot of the stuff I'm working with takes a callback as the final argument so simple calls can be done like this rather than having to wrap everything with an extra function.

2

I know the question is about sleep, and clearly the answer is that it isn't possible. I think a common want for sleep is to handle asynchronous tasks in order; I know I have had to deal with it for sure.

Many cases it may be able to use promises (Ajax requests common use). They let you do asynchronous things in a synchronous manner. There is also handling for success/failure, and they can be chained.

They part of ECMAScript 6, so browser support isn't all there yet, mainly, Internet Explorer does not support them. There is also library called Q for doing promises.

References:

1
  • This should really be a comment, not an answer. Jan 22, 2015 at 18:20
2

With await support and bluebird promise:

await bluebird.delay(1000);

This will work like a synchronous sleep(1) of the C language. My favorite solution.

1
  • If you have await support, you don't need Bluebird. Oct 7, 2016 at 9:48
2

A function to sleep, using a synchronous call to let the OS do it. Use any OS sleep command you like. It is not busy waiting in the sense of using CPU time.

I chose ping on a non-existent address.

const cp = require('child_process');

function sleep(ms)
{
    try{cp.execSync('ping 192.0.2.0 -n 1 -w '+ms);}
    catch(err){}
}

A test to verify it works

console.log(Date.now());
console.log(Date.now());
sleep(10000);
console.log(Date.now());
console.log(Date.now());

And some test results.

1491575275136
1491575275157

(and after 10 seconds)

1491575285075
1491575285076
1
  • But it doesn't work in a web browser context(?). What context does it work in? Jul 6, 2021 at 22:57
2

If you want code that is usable on all browsers, then use setTimeout() and clearTimeout(). If you're reading this far into answers, you'll probably notice that the accepted answer breaks all JavaScript compilation in Internet Explorer 11, and after using this solution, it seems that 5% of users approximately still use this actively-developed browser and require support.

This has broken almost everything. There are known reports of arrow functions breaking Internet Explorer 11 functionality for the software of Drupal, WordPress, Amazon AWS, IBM, and there's even a dedicated discussion on it on Stack Overflow.

Just check it out...

Browser Compatibility Chart - Arrow Function Expressions

Browser Compatibility Chart - setTimeout

Use setTimeout() and clearTimeout(), and that will do the trick for all browsers...

Working JSBin Demo

var timeout;

function sleep(delay) {
    if(timeout) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
        myFunction();
    }, delay);
}

console.log("sleep for 1 second");
sleep(1000);

function myFunction() {
    console.log("slept for 1 second!");
}

1

To keep the main thread busy for some milliseconds:

function wait(ms) {
  const start = performance.now();
  while(performance.now() - start < ms);
}
1
  • 1
    Busy wait? Isn't it already covered by a previous answer? Jul 6, 2021 at 23:05
1

What is the JavaScript version of sleep()?

This has already been answered in the currently accepted answer:

await new Promise(r => setTimeout(r, 1000));

Two asynchronous functions running simultaneously

It is a good idea to put it inside a function sleep(), and then await sleep().
To use it, a bit of context is needed:

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

(async function slowDemo () {
  console.log('Starting slowDemo ...');
  await sleep(2000);
  console.log('slowDemo: TWO seconds later ...');
})();

(async function fastDemo () {
  console.log('Starting fastDemo ...');
  await sleep(500);
  for (let i = 1; i < 6; i++) {
    console.log('fastDemo: ' + (i * 0.5) + ' seconds later ...');
    await sleep(500);
  }
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }

Two asynchronous calls running in sequence – one after the other

But suppose slowDemo produces some result that fastDemo depends upon.
In such a case, slowDemo must run to completion before fastDemo starts:

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

(async () => {
  await (async function slowDemo () {
    console.log('Starting slowDemo ...');
    await sleep(2000);
    console.log('slowDemo: TWO seconds later ... completed!');
  })();

  (async function fastDemo () {
    console.log('Starting fastDemo ...');
    await sleep(500);
    let i = -2;
    for (i = 1; i < 5; i++) {
      console.log('fastDemo: ' + (i * 0.5) + ' seconds later ...');
      await sleep(500);
    }
    console.log('fastDemo: ' + (i * 0.5) + ' seconds later. Completed!');
  })();
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

If you want to sleep an anonymous function like one you've created as a handler, I recommend the following:

function()
{
    if (!wait_condition)
    {
        setTimeout(arguments.callee, 100, /* Comma-separated arguments here */);
    }
    // The rest of the function
}

This code says "If the wait condition has not yet been satisfied, call this function again with these arguments." I've used this method to pass in the same arguments to my handlers, effectively making this code a non-polling sleep() (which only works at the start of your function).

1

A method of an object that needs to use a "sleep" method such as the following:

function SomeObject() {
    this.SomeProperty = "xxx";
    return this;
}
SomeObject.prototype.SomeMethod = function () {
    this.DoSomething1(arg1);
    sleep(500);
    this.DoSomething2(arg1);
}

Can almost be translated to:

function SomeObject() {
    this.SomeProperty = "xxx";
    return this;
}
SomeObject.prototype.SomeMethod = function (arg1) {
    var self = this;
    self.DoSomething1(arg1);
    setTimeout(function () {
        self.DoSomething2(arg1);
    }, 500);
}

The difference is that the operation of "SomeMethod" returns before the operation "DoSomething2" is executed. The caller of "SomeMethod" cannot depend on this. Since the "Sleep" method does not exists, I use the latter method and design my code accordingly.

1

To summarize (like it has been said in previous answers):

There is no built-in sleep function in JavaScript. You should use setTimeout or setInterval to achieve a similar effect.

If you really wanted to, you could simulate sleep functionality with a for loop such as the one shown in the original question, but that would make your CPU work like crazy. Inside a Web Worker an alternative solution would be to make a synchronous XMLHttpRequest to a non-responsive IP address and set a proper timeout. This would avoid the CPU utilization problem. Here's a code example:

// Works only inside a web worker

function sleep(milliseconds) {
    var req = new XMLHttpRequest();
    req.open("GET", "http://192.0.2.0/", false);
    req.timeout = milliseconds;
    try {
        req.send();
    } catch (ex) {

    }
}

console.log('Sleeping for 1 second...');
sleep(1000);
console.log('Slept!');

console.log('Sleeping for 5 seconds...')
sleep(5000);
console.log('Slept!');

1
  • 2
    nice but not possible anymore: ``` Sleeping for 1 second... VM1537 js:17 Uncaught InvalidAccessError: Failed to set the 'timeout' property on 'XMLHttpRequest': Timeouts cannot be set for synchronous requests made from a document.sleep @ VM1537 js:17(anonymous function) @ VM1537 js:26 ```
    – Red Pill
    Jul 17, 2016 at 8:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.