By fmsf


2009-06-04 14:41:10 8 Comments

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.

30 comments

@k06a 2019-11-19 13:34:36

The shortest solution without any dependencies:

await new Promise(resolve => setTimeout(resolve, 5000));

@chaos 2009-06-04 14:44:03

For the love of $DEITY please do not make a busy-wait sleep function. setTimeout and setInterval do everything you need.

var showHide = document.getElementById('showHide');
setInterval(() => {
    showHide.style.visibility = "initial";
    setTimeout(() => {
        showHide.style.visibility = "hidden"
    }, 1000);
    ;
}, 2000);   
<div id="showHide">Hello! Goodbye!</div>

Every two second interval hide text for one second. This shows how to use setInterval and setTimeout to show and hide text each second.

@annakata 2009-06-04 14:48:48

Well not quite everything: setInterval does a much better impression of polling.

@wvdschel 2009-06-04 14:51:10

I sometimes miss a real "sleep", but messing around with setTimeout is still better than actively waiting (like the above while loop). A real sleep function does however not need to freeze the JavaScript engine, but a busy-wait would max out a single CPU core. (And eat up precious battery time of mobile users)

@Deniz Dogan 2009-06-04 14:51:20

What would that piece of code not hold back in the JavaScript engine?

@Aaron Dufour 2011-09-21 16:54:02

Unless you need the sleep to be synchronous, in which case this is a completely valid question.

@chaos 2011-09-21 18:47:43

@Aaron: Since Javascript only supports synchronous sleep by way of hammering the CPU as hard as it possibly can until the sleep duration is over, my sole recommendation for that situation is "redesign until you no longer need synchronous sleep".

@Phil LaNasa 2014-03-02 12:07:49

I think many of us might be forgetting that JavaScript isn't a browser-only language. This dude might be creating a Node command line utility that requires a brief pause without needing to deal with all the variable scoping issues that come with setTimeout.

@chaos 2014-03-03 16:47:28

@PhilLaNasa: If syntactic closure is still scaring one, one seriously needs to buckle down and work through Node 101.

@Phil LaNasa 2014-03-26 20:01:30

@chaos: Completely disagree, closures aren't JS 101. If a novice is looking to write a purely synchronous and simple script, a function like sleep() might come in handy.

@chaos 2014-03-26 21:03:31

@PhilLaNasa: Any context in which closures are not JS 101 needs a full curriculum redesign, stat.

@TechLife 2015-04-04 20:35:08

and what if we wanted to use it in a for loop?

@WGroleau 2018-05-25 20:46:20

My usage is a loop to download hundreds of PDFs from a database whose admin refuses to provide the data in a sensible format. The loop needs a delay between files to ensure little or no overlap.

@chaos 2018-05-31 19:41:25

@WGroleau: This is a classical example of something people think they need sleep for when they don't. You don't need to busywait-lockup the JS engine, you need to split up your processing across setTimeout.

@WGroleau 2018-05-31 21:42:24

It doesn't "lock it up" It starts all the timeouts as fast as it can, and then after the 1.5 second delay, they all try to run at once and only one actually happens. I DID need a delay between downloads in order to actually get them. What does "split it up" mean? Write separate code for each link instead of running a loop? That would take longer than the twelve hundred clicks I was trying to avoid. What finally worked was changing the delay each time: setTimeout({}, 1500*i++);

@Ahmed Mohammedali 2019-06-26 11:27:12

  await new Promise(resolve => setTimeout(resolve, 2000));

make sure your calling function is async

verified and working fine

@Kapytanhook 2019-06-01 11:01:35

2019 Update using Atomics.wait

Should work in Node 9.3 or higher.

I needed a pretty accurate timer in Node.js and it works great for that. However it seems like there is extremely limited support in browsers.

let ms = 10000;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);

Ran a few 10 second timer benchmarks.

With setTimeout I get a error of up to 7000 microseconds. (7ms)

With Atomics my error seems to stay under 600 microseconds. (0.6ms)

@GroovyDotCom 2019-08-04 10:28:27

In my opinion better than the accepted solution which can't be implemented as a simple function without async/await in the caller.

@Kapytanhook 2019-08-06 08:43:26

yeah, as long as you are aware that this is blocking and that usually is not a good thing

@JGreatorex 2019-11-08 12:14:36

Pretty cool, but the fact that this is only really supported in Chrome and Firefox doesn't make it very viable for uses on the web. (Nov 2019)

@Dan Dascalescu 2016-10-07 09:44:56

2017 — 2019 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

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

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later, showing sleep in a loop...');

  // Sleep in loop
  for (let i = 0; i < 5; i++) {
    if (i === 3)
      await sleep(2000);
    console.log(i);
  }
}

demo();

This is it. await sleep(<duration>).

Note that,

  1. await can only be executed in functions prefixed with the async keyword, or at the top level of your script in some environments (e.g. the Chrome DevTools console, or Runkit).
  2. await only pauses the current async function

Two new JavaScript features helped write this "sleep" function:

Compatibility

If for some weird reason you're using Node older than 7 (which has reached end of life), or are targeting old browsers, async/await can still be used via Babel (a tool that will transpile JavaScript + new features into plain old JavaScript), with the transform-async-to-generator plugin.

@Andre Canilho 2016-10-12 02:16:36

Great stuff here. I wonder, how does this affects or relates with the modern browsers "active" / "inactive" states after JS calls the "sleep" mode? Can the browser block the sleep as expected for general JS, to recall later when becomes "active", or does it have a different behavior?

@Alvin Thompson 2016-12-27 17:56:41

What is the current browser support for this? I wouldn't consider the previous solutions to be "obsolete" until this solution is supported by the vast majority of browsers, or at least all of the common ones. On the contrary, I would consider this solution interesting but unusable/impractical until it has widespread support.

@Dan Dascalescu 2017-01-08 10:31:05

@AlvinThompson: the majority of modern web development uses transpilers, so native browser support matters less than cleaner and more future-proof code. Anyway, see caniuse.

@niry 2017-01-11 17:00:05

This is not "real sleep" and does not answer the question. The person who asked made a clear distinct between stackoverflow.com/questions/758688/sleep-in-javascript and his question. In real sleep no other code can be executed (unless in other thread). This answer is good for the other question.

@jacroe 2017-05-19 17:41:55

While Promises can be polyfilled, arrow functions cannot. This is not a viable solution for those having to support IE.

@Jaromanda X 2017-05-30 08:39:21

@jacroe - the transpiler handles arrow functions as well as async/await (which would cause IE to vomit blood anyway)

@user1063287 2017-07-20 02:55:58

Google Apps Script returns Syntax error at the line where the sleep function is defined. (in Chrome 59.0.3071.115 (Official Build) (32-bit))

@phil294 2018-01-17 18:54:45

oneliner await new Promise(r => setTimeout(() => r(), 2000));

@tleb 2018-08-02 22:17:42

Oneliner for the function declaration: const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

@Patrick Roberts 2018-09-13 14:18:29

@niry JavaScript, being a single-threaded language, is not well-suited for "real" sleep, since it runs on the same thread as the UI and would cause unresponsive web pages.

@niry 2018-09-13 21:41:59

@PatrickRoberts, I agree. However, that was the question, extremely clearly.

@nurettin 2018-10-02 10:43:36

why not use promisify?

@Dan Dascalescu 2018-10-05 08:13:04

@tleb: what are the advantages of that syntax vs. the clear function definition from the answer?

@tleb 2018-10-05 09:17:24

@DanDascalescu Personal preference I guess, I don't find the one in the answer clearer.

@Ulysse BN 2018-12-19 17:18:40

All other answers are now obsolete or overly complicated, it really is a matter of taste. Some developers will favor using .then chaining or a callback, I don't see anything complicated with that...

@mythicalcoder 2019-01-14 03:51:53

this is the perfect JS solution.. Other solutions are either outdated or not JavaScript-ly.

@Dan Dascalescu 2019-04-30 17:47:16

@Uciebila: if you await sleep at some point in the loop, the loop will wait the specified amount, then continue looping. Sample code.

@Brian 2019-05-07 01:14:16

I think I'm in the same boat as Uciebila...when I load your sample code at your link, or implement it in my own, all iterations run immediately. Is there a browser dependence here?

@Dan Dascalescu 2019-05-07 03:11:18

@Brian: this appears to be a bug in Runkit. If you're logged out, it somehow skips the await. If you log in and click the ⟲ icon, it works correctly. I've put the code here in the SO code snippet, where it runs as expected. You can also try to copy/paste it in the browser console, or run it in Node on your local machine.

@Anonymous 2019-09-20 20:07:39

Please note that this requires to be ran in an async function

@Jer 2019-10-08 23:05:09

Is there any way to write the sleep function using async/await (i.e. without explicitly constructing a Promise object)?

@Philip Rego 2019-10-19 21:02:37

This is still overly complicated.

@Dan Dascalescu 2019-10-22 06:49:29

@PhilipRego: as far as I know, a simpler version does not exist in JavaScript.

@Philip Rego 2019-10-27 01:35:27

I found using setTimeout() and setInterval() to be simplier, and posted an example here stackoverflow.com/a/951033/1308453

@Ernest 2019-11-22 08:13:41

For Node.js there is package 'delay' npmjs.com/package/delay, await delay(1000)

@Grzegorz 2019-11-23 15:06:17

Note this seems to be working randomly. Using FF 70 and on same browser it works and does not work at same time. On one domain It works ok, on other i get ReferenceError: sleep is not defined so not sure if its not safe to use await sleep

@mukund 2019-03-28 09:19:48

The problem with using an actual sleep function is that JavaScript is single-threaded and a sleep function will pretty much make your browser tab hang for that duration.

@ByteMe 2019-02-26 04:48:57

I got Promise is not a constructor using the top answer. If you import bluebird you can do this. Simplest solution imo.

import * as Promise from 'bluebird';


  await Promise.delay(5000)

@Riccardo Persiani 2019-01-11 11:00:23

I prefer this functional style sleep function:

const sleep = ms =>
    Promise(resolve => setTimeout(resolve, ms))

@Zeel Shah 2019-02-14 07:06:29

This is not sleep funciton. If you call sleep function, it will not wait until time is lapsed, it will execute next instructions immediately.

@Ismail MANAREDDINE 2019-04-10 10:57:47

You can solve this by using "await" .

@MUY Belgium 2018-10-05 14:11:57

A very simple way to do do sleep, that WILL be compatible with anything that runs Javascript... This code has been tested with something like 500 entries, CPU and memory usage still not visible on my web browsers.

Here one function that wait until the node becomes visible...

This function creates a new context function () {} to avoid recursion. We placed a code that does the same as the caller code inside this new context. We use the function Timeout to call our function after a few time second.

var get_hyper = function (node , maxcount , only_relation) {
    if (node.offsetParent === null) {
            // node is hidden
            setTimeout(function () { get_hyper(node , maxcount , only_relation)}
                      ,1000);
            return;
    };

    // Enter here the code that wait that that the node is visible
    // before getting executed.

};

@Franz Kiermaier 2018-09-19 08:28:24

I had a similar problem, having to wait for control existence and checking in intervals. Since there is no real sleep, wait or pause in JavaScript and using await / async is not supported properly in Internet Explorer, I made a solution using setTimeOut and injecting the function in case of successfully finding the element. Here is the complete sample code, so everyone can reproduce and use it for their own project:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        var ElementSearchStatus = {
            None: 0,
            Found: 1,
            NotFound: 2,
            Timeout: 3
        };

        var maxTimeout = 5;
        var timeoutMiliseconds = 1000;

        function waitForElement(elementId, count, timeout, onSuccessFunction) {
            ++count;
            var elementSearchStatus = existsElement(elementId, count, timeout);
            if (elementSearchStatus == ElementSearchStatus.None) {
                window.setTimeout(waitForElement, timeoutMiliseconds, elementId, count, timeout, onSuccessFunction);
            }
            else {
                if (elementSearchStatus == ElementSearchStatus.Found) {
                    onSuccessFunction();
                }
            }
        }

        function existsElement(elementId, count, timeout) {
            var foundElements = $("#" + elementId);
            if (foundElements.length > 0 || count > timeout) {
                if (foundElements.length > 0) {
                    console.log(elementId + " found");
                    return ElementSearchStatus.Found;
                }
                else {
                    console.log("Search for " + elementId + " timed out after " + count + " tries.");
                    return ElementSearchStatus.Timeout;
                }
            }
            else {
                console.log("waiting for " + elementId + " after " + count + " of " + timeout);
                return ElementSearchStatus.None;
            }
        }

        function main() {
            waitForElement("StartButton", 0, maxTimeout, function () {
                console.log("found StartButton!");
                DoOtherStuff("StartButton2")
            });
        }

        function DoOtherStuff(elementId) {
            waitForElement(elementId, 0, maxTimeout, function () {
                console.log("found " + elementId);
                DoOtherStuff("StartButton3");
            });
        }
    </script>
</head>
<body>
    <button type="button" id="StartButton" onclick="main();">Start Test</button>
    <button type="button" id="StartButton2" onclick="alert('Hey ya Start Button 2');">Show alert</button>
</body>
</html>

@Paul Sweatte 2016-07-02 00:25:29

Use three functions:

  1. A function which calls setInterval to start the loop
  2. A function which calls clearInterval to stop the loop, then calls setTimeout to sleep, and finally calls to within the setTimeout as the callback to restart the loop
  3. A loop which tracks the number of iterations, sets a sleep number and a maximum number, calls the sleep function once the sleep number has been reached, and calls clearInterval after the maximum number has been reached

var foo = {};

function main()
  {
  'use strict';
  /*Initialize global state*/
  foo.bar = foo.bar || 0;
  /* Initialize timer */ 
  foo.bop = setInterval(foo.baz, 1000); 
  }
 
 sleep = 
      function(timer)
      {
      'use strict';
      clearInterval(timer);
      timer = setTimeout(function(){main()}, 5000);
      };
       
 
 foo.baz = 
   function()
      {
      'use strict';
      /* Update state */
      foo.bar = Number(foo.bar + 1) || 0; 
      /* Log state */
      console.log(foo.bar);
      /* Check state and stop at 10 */ 
      (foo.bar === 5) && sleep(foo.bop);
      (foo.bar === 10) && clearInterval(foo.bop);
      };
      
main();

Event Loop

References

@CoR 2011-12-03 10:40:21

Code taken from this link will not freeze comp. But it works only on ff.

/**
 * 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 extention for Firefox.
     * Since FF3, 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 finish.
      */
    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);
    }
}

@Taulant 2016-12-22 09:51:47

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

@Harry 2018-06-30 22:06:50

Since Node 7.6, you can combine the promisify function from the utils module with setTimeout.

const sleep = require('util').promisify(setTimeout)

General Usage

async function main() {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
}

main()

Question Usage

async function asyncGenerator() {
    while (goOn) {
      var fileList = await listFiles(nextPageToken);
      await sleep(3000)
      var parents = await requestParents(fileList);
    }
  }

@Stitch 2017-12-19 16:34:30

It is now also possible to use the native module util to promisify regular sync functions.

const { promisify } = require('util')
const sleep = promisify(setTimeout)

module.exports = () => {
  await someAsyncFunction()
  await sleep(2000)
  console.log('2 seconds later...')
}

@chharvey 2018-05-15 15:27:43

you cannot use await inside a non-async function (in your example, the exported function)

@StephaneAG 2013-07-30 00:31:49

Only for debug/dev , I post this if it's useful to someone

Interesting stuff, in Firebug ( & probably other js consoles ), nothing happen after hitting enter, only after the sleep duration specified (...)

function sleepFor( sleepDuration ){
    var now = new Date().getTime();
    while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
}

Example of use:

function sleepThenAct(){ sleepFor(2000); console.log("hello js sleep !"); }

@jab 2015-06-02 04:23:09

This is not an answer. It's exactly the same as the code in the question, except slightly shorter.

@mafu 2016-08-19 12:27:53

Busy waiting, really? In JS? For seconds? If I catch a website doing this, it will be blocked.

@xDaizu 2016-08-29 10:31:22

@mafu That's why it says only for debug/dev... rolleyes

@xDaizu 2016-08-29 10:41:56

@jab That's one of the reasons why I upvoted it. I find hilarious that he optimized his busy waiting loop

@mafu 2016-08-29 15:45:51

@xDaizu I'd be hard pressed to come up with an example of this technique ever being the correct way (or even direction) to solve a problem, regardless if dev or prod.

@xDaizu 2016-08-30 08:25:10

@mafu that's true, it's so tricky to come up with a proper example that it probably deserves its own question!

@Roy Falk 2017-09-11 08:20:20

@mafu it's not tricky at all. As Kee said, it's useful for testing. If you just want to run C after B after A, using promises or callbacks leads you straight to hell. I use it to wait for exec to finish doing something. It means that I can write utility functions and call them as part of a simple script, instead of putting whole chunks of code in callbacks.

@noego 2017-12-18 10:51:13

NEVER DO THIS. This will make the CPU to hit 100% on the core that it executes and will block it.

@Wheezil 2018-01-13 18:52:47

This is useful, and perhaps the ONLY way to sleep, within a command-line javascript application, because async/await is not helpful.

@Nabi K.A.Z. 2018-06-09 04:03:33

The solution is not good, but in some places async/await it's not responsive unfortunately, and we have to use it mandatorily.

@Innokenty 2018-09-12 12:54:19

This actually solves my issue, because that's exactly what I need: busy wait for debug purposes. I can't use await, I don't know why, it doesn't compile. I'm not a js expert, so I better just use this code, thanks!

@pomber 2017-09-27 21:34:38

To keep the main thread busy for some milliseconds:

function wait(ms) {
  const start = performance.now();
  while(performance.now() - start < ms);
}

@Paul Stettler 2017-07-10 19:43:40

Javascript Functions allow no suspension. With synchronous Javascript procedures are implemented. Procedures await i/o operations and sleep timeouts. Available for javascript 1.7.

demos: demo sleep demo suspendable procedures

@CarstenP 2017-06-27 12:18:24

It might me a little late and a little lazy and a little boring or a little intrusive or a little like "back of, bigmouth", but...

Each and any solution I've read so far would be like "let's get to sleep and look what happened, tomorrow".

setInterval(callback, time) would wait time long and then call the callback, WHILE blocking the runtime. The current implementation of "setInterval" is far from being thread-save, not even to mind concurrency.

While the sparse solutions mentioned look like, guess what, C# (laughs), they still don't work like in C#/.NET. They still work like in C.

JavaScript currently does NOT provide an architecture to accomplish real multi-threading. The best approach would be TypeScript, but still this lacks so much of a real solution that it... hurts. JavaScript, and jQuery, and AJAX, and jNode, and even TypeScript are just a bunch of Wannabes relying on the goods and bads of the moods of the implementors. Fact. Full stop.

@Shadow 2019-06-14 03:58:30

setInterval does not block - and more importantly, it repeats every time. This isn't even close to what is being asked.

@Ivan 2017-04-07 14:39:36

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-existant 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

@God Ѻ 2017-04-04 15:01:20

I have had this question for a long time and the answer I needed was not exactly what has been provided here. This wait function causes a synchronous wait that does not tie up the cpu. waitForIt makes an ajax request to anywhere and sets the async flag to false. waitF does the same with a frame and waitD does the same with a div. Ajax takes about 100 ms, frame is about 25, and div is about 1. The wait function leverages all of these depending on how much time you give it. If it didn't wait long enough then do it again. I need this when dealing with multiple asynchronous loading elements. Basically for 'wait until this element exists'. You can play with it here https://jsfiddle.net/h2vm29ue/ It just leverages the things that the browser naturally waits for. Longer version https://jsfiddle.net/5cov1p0z/32/ is more precise.

 function waitForIt() {
     var start = new Date();
     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
            //doesn't matter
         }
     };
     xhttp.open("GET", "WaitForIt", false);
     xhttp.send();
     var end = new Date();
 }
 //



 function waitF() {
     var start = new Date();
     var ifram = document.createElement('iframe');
     ifram.id = 'ifram';
     ifram.src = '';
     var div = document.createElement('div');
     div.id = 'timer';
     document.body.appendChild(div);
     document.getElementById('timer').appendChild(ifram);
     document.getElementById('timer').removeChild(ifram);
     document.body.removeChild(div);
     var end = new Date();
     return (end - start);
 }


 function waitD() {
     var start = new Date();
     var div = document.createElement('div');
     div.id = 'timer';
     document.body.appendChild(div);
     div.click();
     document.body.removeChild(div);
     var end = new Date();
     return (end - start);
 }

 function wait(time) {
     var start = new Date();
     var end = new Date();
     while ((end - start < time)) {

         if ((time - (end - start)) >= 200) {
             waitForIt();
         } else {
             if ((time - (end - start)) >= 50) {
                 waitF();
             } else {
                 waitD();
             }

         }
         end = new Date();
     }
     return (end - start);
 }

@Ben Flynn 2011-05-13 13:21:37

(See the updated answer for 2016)

I think it's perfectly reasonable to want to perform an action, wait, then perform another action. If you are used to writing in multi-threaded languages, you probably have the idea of yielding execution for a set amount of time until your thread wakes up.

The issue here is that JavaScript is a single-thread event-based model. While in a specific case, it might be nice to have the whole engine wait for a few seconds, in general it is bad practice. Suppose I wanted to make use of your functions while writing my own? When I called your method, my methods would all freeze up. If JavaScript could somehow preserve your function's execution context, store it somewhere, then bring it back and continue later, then sleep could happen, but that would basically be threading.

So you are pretty much stuck with what others have suggested -- you'll need to break your code up into multiple functions.

Your question is a bit of a false choice, then. There is no way to sleep in the way you want, nor should you pursue the solution you suggest.

@Didier A. 2013-08-16 19:20:56

This is not a correct answer at all. If Javascript does not have a sleep function, it is only because ECMAScript does not require it. It is a design choice by the body responsible for the design of Javascript. It could have been made that the Javascript run time waits a given amount of time before running the next line of code, but it was chosen not to.

@Lawrence 2013-11-14 12:40:52

A sleep can be perfectly implemented in JavaScript allbeit not with real-time precision. After all it is an event based system. If async calls are completed an event is triggered. I see no reason why the same can't be possible when a sleep() is issued after which control is returned to the browser until the sleeping is over, returning control to the calling function. And yes, I also agree that sometimes sleeping is handy especially when developers BEFORE you screwed up the design so badly that YOU have no other way out besides completely refactoring for which you have no time

@Tezcat 2013-12-05 10:34:18

Try Hypnotic, which follows this idea: coolwanglu.github.io/hypnotic/web/demo.html

@Jameson Quinn 2014-08-09 15:12:54

There is one situation where timeouts simply don't solve the problem, no matter how much you refactor: if you're running server-side, the client is waiting for the data, and you don't have direct access to the connection to pass it to the timeout callback. For instance, in meteor, you could be running in a method. In that case, you should consider using a future, as described here: stackoverflow.com/questions/12569712/…

@Benubird 2015-01-29 15:06:15

Calling javascript single-threaded is a but of a myth. While it may be technically correct, functionally it acts like a multithreaded langauge. Simulating a fork() is trivially easy, and although yield() isn't really implementable, you can get pretty close by using shared memory to lock/semaphore. For the average programmer, it makes sense to treat it as multi-threaded; the technical name only matters to the developers of the language.

@Beejor 2015-09-12 05:10:58

I agree why sleep() isn't possible in JS, and that most of the time there are better ways to do things. But I'd still consider the way the engine ties all things up to be a design flaw; there's no reason the language couldn't have a sleep() function limited to a specific script, page, or function without the engine clobbering the CPU and freezing the app like a maniac. It's 2015 and you shouldn't be able to crash an entire web browser with while(1). We have Flash for things like that.

@Akelian 2016-11-12 19:56:33

I personally like the simple:

function sleep(seconds){
    var waitUntil = new Date().getTime() + seconds*1000;
    while(new Date().getTime() < waitUntil) true;
}

then:

sleep(2); // Sleeps for 2 seconds

I'm using it all the time to create fake load time while creating scripts in P5js

@hegez 2017-10-27 16:45:02

I see this as the most optimized version of the main question: it does not do any maths inside the loop, just a plain comparison. It's a bit difficult to read tho.

@noego 2017-12-18 10:46:05

NEVER EVER DO THAT. Have you checked the CPU usage while this function is working? It should be close to 100% if you give enough time for it.

@ShadowRanger 2018-12-14 01:27:13

@hegez: Given the loop is going to run for a fixed amount of wall clock time no matter what, it seems like optimizing the loop is kind of beside the point.

@O_Z 2016-10-13 14:31:04

The problem with most solutions here is that they rewind the stack. This can be a big problem in some cases.In this example I show how to use iterators in different way to simulate real sleep

In this example the generator is calling it's own next() so once it's going, it's on his own.

var h=a();
h.next().value.r=h; //that's how U run it, best I came up with

//sleep without breaking stack !!!
function *a(){
    var obj= {};

    console.log("going to sleep....2s")

    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

    console.log("woke up");
    console.log("going to sleep no 2....2s")
    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

     console.log("woke up");
    console.log("going to sleep no 3....2s")

     setTimeout(function(){obj.r.next();},2000) 
     yield obj;

    console.log("done");

}

@bitifet 2016-10-14 06:12:28

At server side, you can use the deasync sleep() method, which is natively implemented in C so it can effectively implement a wait effect without blocking the event-loop or putting your CPU at 100% of load.

Example:

#!/usr/bin/env node

// Requires `npm install --save deasync`
var sleep = require("deasync").sleep;

sleep(5000);

console.log ("Hello World!!");

But, if you need a pure javascript function (for example, to run it at client-side by a browser), I'm sorry to say that I think your pausecomp() function is the only way to approach it and, more than that:

  1. That pauses not only your function but the whole event loop. So no other events will be attended.

  2. It puts your cpu at 100% load.

So, if you need it for a browser script and doesn't want those terrible effects, I must say you should rethink your function in a way:

a). You can recall it (or call a do_the_rest() function) at a timeout. The easier way if you are not expecting any result from your function.

b). Or, if you need to wait for a result, then you should move to using promises (or a callback hell, of course ;-)).

No result expected example:

function myFunc() {

    console.log ("Do some things");

    setTimeout(function doTheRest(){
        console.log ("Do more things...");
    }, 5000);

    // Returns undefined.
};


myFunc();

Example returning a promise (notice it alters your function usage):

function myFunc(someString) {

    return new Promise(function(resolve, reject) {

        var result = [someString];
        result.push("Do some things");

        setTimeout(function(){
            result.push("Do more things...");
            resolve(result.join("\n"));
        }, 5000);

    });

};


// But notice that this approach affect to the function usage...
// (It returns a promise, not actual data):
myFunc("Hello!!").then(function(data){
    console.log(data);
}).catch(function(err){
    console.error(err);
});

@Nosredna 2009-06-04 14:46:54

In JavaScript, I rewrite every function so that it can end as soon as possible. You want the browser back in control so it can make your DOM changes.

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().

I am going to edit this answer because i found this as useful:

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:

// sleep time expects milliseconds
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

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

@David Dombrowsky 2010-03-16 20:34:17

this solution doesn't work if you have any state variables. If the function you're trying to sleep has any parameters. For example, how can one do fuction foobar(el){ setTimeout(foobar_cont(el),5000); } ??? I haven't figured that out yet.

@chaos 2010-04-08 03:27:18

By way of closure. function foobar(el) { setTimeout(function() { foobar_cont(el); }, 5000); }

@Eugenio Miró 2010-07-22 15:23:46

ok, and what if the code is not intended to be used in a webpage?

@Timofey 2011-01-26 07:36:12

@chaos: the function foobar_con takes the value of el at the moment of invocation of function foobar_con, but not unfortunately of the function foobar. Good example is a loop where el is changing: all the delayed function invocations of foobar_con will be with the maximal value of el.

@BrainSlugs83 2011-09-24 00:57:45

@EugenioMiró if the code is not intended to be used in a webpage, have the host's object model implement a sleep method. -- I think the question is geared towards the DOM which is exposed to javascript running on web pages.

@BrainSlugs83 2011-09-24 00:59:33

@Nosredna yes, we understand how to make async calls, this doesn't help us sleep(). I want my calls to be made in a certain order, and to have the data back in a certain order. I'm 5 levels deep in a for loop. I want to BLOCK execution. A true sleep method would not "slow down the browser", sleep hands control back to the browser and any other threads that want CPU time while it is still blocking.

@TMS 2011-11-24 13:22:23

this is not an answer to the question.

@sorki 2011-12-28 22:45:33

@Tim loop-safe version: for(i=0; i<5; i++) { (function(i) { setTimeout(function() { console.log(i); }, 1000*i); })(i); }

@Eugenio Miró 2012-02-28 12:54:30

@Morg sorry to disagree with you, I need a solution like this in an environment different than an webpage, please, if you don't like my comment please skip it, I come here to find answers not to read comments like yours. Thanks.

@Morg. 2012-04-10 15:15:59

@EugenioMiró ; my bad, I probably used the wrong words. Your question is unrelated to the question that was answered here, trying to extend the scope by asking a question in the comments is a bad idea, you should create a new question about node.js or w/e server-side js technology you're using in order to get a real answer.

@Eugenio Miró 2012-04-11 00:26:04

ok @Morg, you're right, but as I saw the title was related to javascript and sleep I though it was not only a solution for a web page, I could ask something by myself instead of asking in a comment. Thanks for your suggestion.

@Jelgab 2013-04-04 16:03:34

How would one approach the following cases: 1. During testing the developer wants to simulate that clicking a button calls a process that takes real long and requirements do not allow to either change the way the process is called or to call it asynchronously 2. After clicking a button, some changes happen on the page (like a "please wait..." message that the user will randomly see depending on how busy is the server at the moment but right now the developer wants to visually test the message simulating the server is busy.

@Glenn Plas 2013-11-24 13:46:37

good comment Jelgab, you can tell you are a developer. In case someone want's to block the browser on an ajax call, it would be so simple to switch off async on that call: $.ajax({ 'async': false });

@Tezcat 2013-12-05 10:35:59

Try this almost answer: Hypnotic. coolwanglu.github.io/hypnotic/web/demo.html

@Anonymous Pi 2014-01-09 15:18:34

@Tezcat I'm making a .html (no hosting) but sadly, all the familiars I send them to use Chrome ;(

@Enissay 2014-05-22 00:47:29

To call functions with parameters using the same code above use for example: foobar_cont_2.bind(this, "value")) to call the function foobar_cont_2(xXx)

@arcseldon 2014-05-31 00:57:51

The function assigned to the setTimeout is put onto an event queue. JavaScript is inherently single-threaded. If there’s at least one event on the queue that’s eligible to “fire” (like a 3000ms timeout that was set 4000ms ago), the "javascript VM" will pick one and call its handler (function callback). The point is that the actual call will unlikely be precisely when you requested it (say 3000 milliseconds later), it might be 3001, 3002 or even quite a bit later depending on number and nature of other events on the queue, & the duration of their callbacks

@rlemon 2014-07-16 13:25:17

am I the only one to notice the sleep function is identical to just using setTimeout (minus the reversed arguments) ??

@Joe 2014-10-28 06:24:50

@rlemon the original answer just referred to setTimeout and is ok, because it's just an opinion. But the edit misdirects the reader to think that there is a equiv sleep, which is just a call to setTimeout... it's a bad joke really because it wastes ppl's time in reading and understanding... essentially nothing.

@user508633 2015-01-06 07:06:07

True (synchronous) sleep is useful in testing, e.g. to simulate a long-running JS task. Many eventing bugs arise due to heavy JS tasks (e.g. backend requests with large payloads that need processing or unbatched processing on very large pages). Synchronous sleep is useful for testing + repro in such cases.Should never run in production code, but far from useless.

@TechLife 2015-04-04 20:35:21

and what if we wanted to use it in a for loop?

@Memet Olsen 2015-12-16 07:27:50

setTimeout doesnt SLEEP in the middle of your function as you've stated. Your function continues executing. Everything else inside the setTimeout will get executed later on.

@David Rivers 2016-05-30 17:38:14

A good while ago, I flagged this as being "not an answer", only to have the author of this answer (@Nosredna, I'm looking at you) to decline this flag with a cheap-ass "declined - Seriously?". Clearly @Nosredna has a conflict of interest--he would rather preserve his upvotes than help other users/Web browsers find the best answer to this question. This is the first time I've noticed a misuse of bureaucratic power on a SE site, but I will pay more attention. This kind of BULLSHIT is exactly why I stopped contributing to WikiMedia projects a long time ago!

@Deepak Sharma 2016-07-04 05:32:47

this can be done using JavaScript Promises. I have added the answer. this works.

@user664833 2016-09-06 07:32:22

@BrainSlugs83 "I'm 5 levels deep in a for loop. I want to BLOCK execution." ...How about alert("hi, i'm blocking execution");? ...When the alert pops up, and without dismissing it, I can still access Chrome's console and do debugging.

@Souvik Ray 2019-11-15 07:43:26

This is what I was looking for. Works perfect!

@Dalibor 2019-11-15 20:44:26

I dont understand whats the point by wrapping one async function inside another async function and call it a sleep? As far as I know sleep should suspend execution of the current thread. And async functions, as setTimeout or Promise constructor are doing quite opposite, they DO NOT suspend execution, instead they postpone some processing by adding it to the event queue.

@a_w 2011-06-14 20:50:28

I've searched for sleep solution too (not for production code, only for dev/tests) and found this article:

http://narayanraman.blogspot.com/2005/12/javascript-sleep-or-wait.html

...and here's another link with client-side solutions: http://www.devcheater.com/

Also, when you are calling alert(), your code will be paused too, while alert is shown -- need to find a way to not display alert but get the same effect. :)

@user435779 2012-10-17 15:03:10

I agree, lots of people are saying, "No, don't do this in production code!" Yeah, um, I don't want to. I want to do it in throwaway test code, and as a result I don't want to spend a lot of time making an elegant solution.

@Guang-De Lin 2016-08-29 10:26:53

With await support and bluebird promise:

await bluebird.delay(1000);

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

@Dan Dascalescu 2016-10-07 09:48:54

If you have await support, you don't need Bluebird.

@1j01 2015-01-04 04:41:17

A lot of the answers don't (directly) answer the question, and neither does this one...

Here's my two cents (or functions):

If you want less clunky functions than setTimeout and setInterval, you can wrap them in functions that just reverse the order of the arguments and give them nice names:

function after(ms, fn){ setTimeout(fn, ms); }
function every(ms, fn){ setInterval(fn, ms); }

CoffeeScript versions:

after = (ms, fn)-> setTimeout fn, ms
every = (ms, fn)-> setInterval fn, ms

You can then use them nicely with anonymous functions:

after(1000, function(){
    console.log("it's been a second");
    after(1000, function(){
        console.log("it's been another second");
    });
});

Now it reads easily as "after N milliseconds, ..." (or "every N milliseconds, ...")

@Spaceboy Ross 2016-05-31 01:01:13

This might work. It worked for me in c and javascript.

function sleep(time) {
 var x = 0;
 for(x = 0;x < time;x++) {/* Do nothing*/}
}

@Alwin Kesler 2016-06-02 14:55:27

The use of a for/while/foreach should be avoid in javascript. Consider setTimeout() or setInverval() instead

@Shadow 2019-06-14 03:59:59

This will block for an arbitrary amount of time, according to how fast the user's processor can count. I don't imagine many people will find this helpful.

Related Questions

Sponsored Content

89 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6157592 View
  • 7682 Score
  • 89 Answer
  • Tags:   javascript arrays

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

41 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

36 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 508449 View
  • 2914 Score
  • 36 Answer
  • Tags:   javascript operators

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

Sponsored Content