sleep() in JavaScript

March 24th, 2008. Tagged: JavaScript, performance

PHP has a sleep() function, but JavaScript doesn't. Well, this is because it's useless, you might say, and you'll be right. But for simulating heavy processing and for misc performance measurements, it could be useful. So here's how you can go about creating a sleep() in JavaScript.

The code

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Usage

Sleep for 1 second (1000 milliseconds):

console.log(new Date());
console.log('Dude!');
sleep(1000);
console.log(new Date());

Result in Firebug's console:

sleep.png

Tell your friends about this post: Facebook, Twitter, Google+

33 Responses

  1. Eek! That will kill the browser and possibly the machine. Javascript is single threaded, so the browser will block while this executes, and the loop itself will just take up a lot of CPU. I’ve heard of some libraries that actually do sleep correctly in an asynchronous manner, but I can’t remember the name right now.

  2. You mean sleep while not actually freezing, but just sitting idle? Interesting…

  3. @Stoyan: to me a while loop feels more natural:

    function sleep(milliseconds) {
    var start = new Date().getTime();
    while ((new Date().getTime() - start) < milliseconds){
    // Do nothing
    }
    }

    console.log(new Date());
    sleep(5000);
    console.log(new Date());

    Tue Mar 25 2008 08:36:54 GMT+0000 (BST)
    Tue Mar 25 2008 08:36:59 GMT+0000 (BST)

    I’m thinking a non-blocking solution could look like this:

    function sleep(milliseconds) {
    setTimeout(function(){
    var start = new Date().getTime();
    while ((new Date().getTime() - start) < milliseconds){
    // Do nothing
    }
    },0);
    }

    console.log(new Date());
    sleep(5000);
    console.log(new Date());

    The script returns after the sleep but the second logged date is the same as the first:

    Tue Mar 25 2008 08:34:51 GMT+0000 (BST)
    Tue Mar 25 2008 08:34:51 GMT+0000 (BST)

  4. Thanks Stuart, both very good points.

  5. I second what Philip said — This is a very bad idea. JavaScript is single threaded so while that for loop is running nothing else can execute (js timers, browser events, even the UI in most browsers). Try to sleep for 5 or more seconds and the browser will even warn the user that a script is running slowly.

    Just use setTimeout.

    If you really want a sleep function then try “Narative JavaScript” here: http://www.neilmix.com/narrativejs/doc/index.html. It’s a pre-proccessor that allows you to use blocking code that it then changes to async code for you.

  6. Thanks for the link Jason.

    The thing I had in mind is that sometimes that’s exactly what scripts do, they are so busy that they freeze that browser for a part of a second or two. For performance experiments that’s what I wanted to simulate: a very busy script that locks the browser.

    I don’t think setTimeout will simulate exactly that. As Stuart shows above, if you use setTimeout() with even 0 milliseconds delay, this tells the browser: “finish what’re doing and when you have a chance, execute what I’ve set with a timeout”. In Stuart’s example the two dates are logged (part of the current thread) and the sleep happens right after that.

  7. Ok, fair enough. I would just put something that says “Don’t actually do this unless you know what your doing”. Someone who doesn’t understand js internals might use your function when they really should use setTimeout.

  8. This approach didn’t work for me because it blocked the whole CPU. I have a “Print this page” button that does an onclick to a javascript function that includes a window.print(). But prior to the window.print() I need to change document.form1.creditcard.value so that only the last 4 digits appear, e.g., xxxx-xxxx-xxxx-2080. Then after the window.print() I want to restore document.form1.creditcard.value. What I find is that evidently window.print() executes as a rather slow separate thread, so the credit card number is restored BEFORE the print function has a chance to capture the modified value. What I need is a blocking delay of about 4 seconds, but not a blocking delay that also blocks the print function. The only solution I’ve found is to pop up an alert box that tells the users to click after 4 seconds. Ugh!

  9. Oh thanks so much for this code, you are a lifesaver! Keep up the good work with your blog.

  10. Yes, unfortunately it boosts the CPU’s load at over 90% and is not asynchronous. Perhaps you should name the function “wait”.

  11. Everyone who is saying this function doesnt work like ti should is wrong.

    This is 100% what it should do. Notice he says he is making a sleep function that behaves like the PHP sleep() function, and it does.

    Thanks for it!

  12. @Marc: “Notice he says he is making a sleep function that behaves like the PHP sleep() function, and it does.” Does PHP’s sleep() function peg your CPU at 100% while it’s sleeping? That’s the issue here. This is appropriate for his testing use, but not for anything you’d want to inflict on a regular website user. +1 for marking this “do not use unless you really know what you’re doing.”

  13. Unfortunately, this is not a sleep. This is a wait. A “sleep” function should idle the processor for a specified time, not blast it into oblivion with work.

    Looking for a proper sleep() for JavaScript is becoming tiresome, and JS programmers are retarded and say things like “JUST USE SETTIMEOUT()” because that’s not always the *right* way to do something.

    For instance, I have a JavaScript app I’m writing right now that loops through about 1500 XML elements to prepare to add markers to a google map. During this process loop, CPUs are maxed out. I want to add an ACTUAL sleep for about 1-5 milliseconds (as in, a wait state where no processing is going on) to the loop to throttle back the CPU load to avoid killing peoples’ browsers. Unfortunately, it does not seem possible.

  14. In your case looks like setTimeout is the thing to do. JS is single-threaded, but you have two options. For latest/greatest browsers there are the web workers – https://wiki.mozilla.org/DOMWorkerThreads_current

    Otherwise, setTimeout with a 1ms timeout will allow you to unlock the thread and not block the UI. so the recipe is
    1. do a chunk of computation
    2. setTimeout to schedule the next part in 1ms
    … repeat till work is done

  15. Okay, so here’s the deal with a real sleep vs. setTimeout scenario – I have functionality where under a certain condition I need to display a “modal” dialog box. Because of the complexity of what needs to be displayed inside this box, I cannot use “alert()”, “confirm()” or “prompt()”. However, I need the current JavaScript thread to halt (yes, I understand that JavaScript is single-threaded, although the inclusion of “setTimeout” and “setInterval” would suggest otherwise) until the box has received all the required input, and has been closed (identical to how “alert()”, “confirm()” and “prompt()” operate, so for the love of all that is holy, don’t “use setTimeout” me – I’ve explored using that for a week, and it’s NOT a viable solution for me).

    Frankly, the amount of quirky coding required to facilitate my needs using setTimeout would be arduous, and would require some truly screwed up process flow – all for the sake of avoiding a “useless” instruction such as “sleep”/”wait”/whatever. It’s OBVIOUSLY something which is required, otherwise JavaScript wouldn’t include “alert()”, “confirm()” and “prompt()”, functions which are designed to offer exactly this sort of functionality, but which are overly simplified.

  16. This site shows you a few different ways of creating a sleep function in JavaScript. And how each one affects the browser.

    http://www.devcheater.com

    In the end the only thing that is cross browser safe is the setTimeout() and setInterval() functions.

  17. therealdealsince1982

    I have searched/googled quite a few webpages on javascript sleep… and there is no answer if you want javascript to “RUN, DELAY, RUN”… what most people got was either, “RUN, RUN(useless stuff), RUN” or “RUN, RUN + delayed RUN”….

    So I ate some burgers and got thinking:::
    here is a solution that works… so you need to chop up your running codes…:::

    DISPLAY

    //javascript sleep by “therealdealsince1982″; copyrighted 2009
    //setInterval
    var i = 0;

    function run() {
    //pieces of codes to run
    if (i==0){document.getElementById(“id1″).innerHTML= “code segment “+ i +” is ran”; }
    if (i==1){document.getElementById(“id1″).innerHTML= “code segment “+ i +” is ran”; }
    if (i==2){document.getElementById(“id1″).innerHTML= “code segment “+ i +” is ran”; }
    if (i >2){document.getElementById(“id1″).innerHTML= “code segment “+ i +” is ran”; }
    if (i==5){document.getElementById(“id1″).innerHTML= “all code segment finished running”; clearInterval(t); } //end interval, stops run
    i++; //segment of code finished running, next…
    }

    t=setInterval(“run()”,1000);

    //…………………………

    DISPLAY

    //javascript sleep by “therealdealsince1982″; copyrighted 2009
    //setTimeout
    var i = 0;

    function flow() {
    run(i);
    i++; //code segment finished running, increment i; can put elsewhere
    sleep(1000);
    if (i==5) {clearTimeout(t);} //stops flow, must be after sleep()
    }

    function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    if (segment==1){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    if (segment==2){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    if (segment >2){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    }

    function sleep(dur) {t=setTimeout(“flow()”,dur);} //starts flow control again after dur

    flow(); //starts flow

    //…………………………………………

    DISPLAY

    //javascript sleep by “therealdealsince1982″; copyrighted 2009
    //setTimeout, switch
    var i = 0;

    function flow() {
    switch(i)
    {
    case 0:
    run(i);
    sleep(1000);
    break;
    case 1:
    run(i);
    sleep(2000);
    break;
    case 5:
    run(i);
    clearTimeout(t); //stops flow
    break;
    default:
    run(i);
    sleep(3000);
    break;
    }
    }

    function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    if (segment==1){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    if (segment==2){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    if (segment >2){document.getElementById(“id1″).innerHTML= “code segment “+ segment +” is ran”; }
    i++; //current segment of code finished running, next…
    }

    function sleep(dur) {t=setTimeout(“flow()”,dur);} //starts flow control again after dur

    flow(); //starts flow control for first time…

  18. The whole CPU!

  19. This is my go @ it. I needed something quite different from what you needed.

    /*
    * Sleep while condition == true
    * @param int interval – interval between every time sleep checks for condition (MS)
    * @param function/string condition – function that should return wether to continue looping or not. Beware of the scope of variables.
    * @param function/string onFalse – function to be executed when conditions return false. Expects a string like “function()” or a function.
    */
    function sleep_while(interval, condition, onFalse) {
    if(eval(condition)) {
    setTimeout(“sleep_while(“+interval+”, “+ condition + “, ” + onFalse + “)”, interval);
    } else {
    if(typeof( onFalse ) == ‘string’) {
    eval(onFalse);
    } else {
    onFalse();
    }
    }
    }

  20. Thanks, the original code posted here works great for my purpose. I don’t care about syncro, asyncro, nor any other sink. Like one person implied above, maybe we should not “…actually do this unless you know what your doing.” Great idea – then we learn nothing.

  21. Still Wondering

    So… I have a loop that goes really fast, it changes a line in the page repeatedly, but it does it too fast to read.

    It needs to wait a second each time before reprinting the updated text.

    If I use a while loop with Date().getTime() to wait it clobbers the CPU and everything stops in other tabs/pages (eg music/video playing is affected).

    If I use setTimeout(fn,1000) I only see the last one, because all the times are 1 second later, but still only a very short time apart – the time of a loop which still has not changed!

    There must be a way to do this, or is Javascript really that lacking?

  22. When your sleep function executes, it uses the CPU 100%. (stating the obvious). For example if you set a sleep function for two minutes, your clients browser won’t be able to load the page completely for at least two minutes because it has to wait for your javascript function to finish itself.
    Illustrated example on page three and four: http://www.google.com/googlebooks/chrome/big_02.html

    There are two solutions:
    1. Multi-threading. This means that your javascript can execute while the browser is loading the page at the same time. The browser still won’t be able to execute the rest of your javascript until your sleep function is done. This is inferior to solution 2

    2. Use setTimeout(foo, bar) and setInterval(foo, bar). setTimeout will execute foo after bar miliseconds AND continue with your javascript code while its waiting. setInterval will repeat foo every bar miliseconds until clearInterval() is called.
    @Still Wondering, Use setInterval instead of setTimout
    http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
    The deal with setTimout is that the statements after setTimeout are not delayed. ONLY the foo statement is delayed. This is good because it doesn’t block up the rest of the flow. It just delays one statement. If you want more statements to be delayed (the entire thing maybe?), you can make an anonymous function

    blah;
    blah; //run normally
    setTimout(function() {
    blahdelayed; //these statements are delayed 1000 seconds.
    blahdelayed;
    }, 1000);

  23. Still Wondering::

    var t = new Date().getTime();
    var div = document.getElementById(‘a’);
    function sleep() {

    var s = new Date().getTime();

    div.innerHTML += “Old time ” + t +”";
    div.innerHTML += “New time ” + (s – t)+”";

    window.setTimeout(“sleep();”,1000);
    }

    sleep();

  24. I need to sleep, need to sleep, need some sleep, can’t sleep, why can’t I sleep, how to sleep better, lack of sleep…

    [...]sleep() in JavaScript / Stoyan’s phpied.com[...]…

  25. Hi,

    If you need sleep function – you can send sync request to server …
    function sleep(milliseconds) {
    //code here for you SYNC request to server /*asp.net or php*/
    }

    it’s works,browser block all events until http response.

  26. You are really looking into this the wrong way…
    A correct (non-blocking) way of doing this is the following:
    function sleep(miliseconds, callback){
    setTimeout(callback,miliseconds);
    }
    //and then use it as follows:
    sleep(5000, function(){
    alert(‘Wow, nice sleep’);
    });
    this works in all browsers (for so far I’ve tested it) and is both UI-safe and simple to use. Just remember to use a function as a variable which is then passed to the setTimeout function and you’re set.

  27. [...] From phpied.com: [...]

  28. very first solution won’t work if the required sleep duration is a big number(say 5 mins). Below modified code will solve the problem:

    function sleep(milliseconds)
    {
    var startTime = new Date().getTime();
    for (var i = 0; i milliseconds)
    break;
    else if ( i == (1e7-1) )
    i =0;
    }
    }

  29. function sleep(milliseconds)
    {
    var startTime = new Date().getTime();
    for (var i = 0; i milliseconds)
    break;
    else if ( i == (1e7-1) )
    i =0;
    }
    }

  30. rrrrrrrrrrrrr

  31. Hi there, You have done an excellent job. I’ll definitely digg it and personally recommend to my friends. I’m sure they will be benefited from this site.

  32. This is a VERY interesting approach. I dig it. Unfortunately, it looks like Chrome is now intercepting the possibility of an “endless loop” and exits the function on your behalf.

    http://jsbin.com/odesOlaQ/1/edit

  33. Thanks man, you have saved me… i had a problem related to this topic and my boss was pushing.
    I´m a begginer in the programming world… therefore in the name of the noobs i thak to you.

Leave a Reply