346

I have a JavaScript code that I need to add a sleep/wait function to. The code I am running is already in a function, eg:

function myFunction(time)
{
    alert('time starts now');
    //code to make the program wait before continuing
    alert('time is up')
}

I have heard that a possible solution might include

setTimeout

but I am not sure how to use it in this case.

I can't use PHP, as my server does not support it, although using jQuery would be fine.

Gottlieb Notschnabel
  • 8,768
  • 17
  • 66
  • 107
user2370460
  • 6,320
  • 7
  • 27
  • 40
  • The code would be `setTimeout(function(){ alert('time is up')},time);` (instead of the `\\` line and the `alert` line below it), time is given in miliseconds https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout – Benjamin Gruenbaum Jun 01 '13 at 13:43
  • 1
    For which reason would you have to make your script wait? – A. Wolff Jun 01 '13 at 13:43
  • Thanks everyone. Would it be possible to make a function sleepNow(time), that you can call within the script, such as sleepNow(5000) to sleep 5 seconds? – user2370460 Jun 01 '13 at 14:07
  • 2
    function sleep( _ms = 0 ) { var _start = new Date().getTime(); while( _ms > ( new Date().getTime() - _start ) ){} } – Sandro Rosa Jun 04 '18 at 17:09
  • I would like to reopen this questions. Becauae here we can give answers that relevant only to browsers, – Aminadav Glickshtein Sep 08 '19 at 06:13

1 Answers1

624

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

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

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

BeNdErR
  • 15,879
  • 16
  • 63
  • 97
  • 28
    It freezes browser, and if you do `sleep` more than 10 seconds, browser shows alert: `A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.`. – Ikrom Jun 01 '13 at 15:55
  • JS is single threaded.. use short periods of time or find another way involving setTimeout function. have a look here: http://stackoverflow.com/questions/8624427/javascript-sleep-with-settimeout – BeNdErR Jun 01 '13 at 16:04
  • 90
    Hello! This is a busy wait loop. Surely it cannot be the accepted answer. – Old Geezer Nov 19 '13 at 01:41
  • I needed a blocking sleep to test if an error was due to a time consuming task or doing an async call returning the flow of the application. Ultimately my program will not include this function but it will help me debug. – Jake Dec 14 '13 at 21:55
  • 10
    this locks the browser, is cpu intensive, causes execution interruption on mobile devices if paused time is too long – Paolo Jan 26 '14 at 11:24
  • 27
    `setTimeout()` involves callbacks, which means it is asynchronous. The OP asked for something that halts, which is synchronous and will cause interruption. – Ilan Biala Mar 04 '14 at 22:51
  • 2
    @BeNdErR, its better to use infinite loop with `while(true)` instead of `for(..)`. So that your page will respond even with big delays. – IvanZh May 27 '14 at 06:51
  • 1
    @IvanZh can you explain why `while` will respond better than `for` on big delays? – BeNdErR Jun 16 '14 at 08:49
  • 3
    @BeNdErR, using infinite loop you will never reach the last 'i' value. I tested `for` loop with `< 1e7` and it takes less then 20 sec in Chrome. So, I think, its better to use infinite loop or `< Number.MAX_VALUE`. – IvanZh Jun 16 '14 at 13:42
  • 4
    -1 Horrible that this starts with a sleep function that is a busy loop. Scary that 30 people have +1'd this. I hope future readers read on to the setTimeout example that was added a year later. – ToolmakerSteve Aug 12 '14 at 02:28
  • 34
    I was looking for a busy loop for debugging purposes so even if this is not meant to be used in a production environment it's exactly what I was looking for. – flu Apr 01 '15 at 09:47
  • 3
    It is totally a valid answer to accept because it answers the question. I found it in the context of browser automation, where pausing the entire UI for 1 second is totally fine. It is also important to highlight the answer to ensure that people understand what the actual question is and the consequence of this answer, which has been done. – Eric J. Sep 18 '15 at 16:58
  • It would be a good idea to call the method "blockingSleep", to avoid tempting people to use it in the wrong context. A bit like react.js' dangerouslySetInnerHTML. – Nicola Marcacci Rossi Oct 13 '15 at 07:37
  • 2
    I will also say that not all JS is client-side and there *are* some definite cases in which, when reaching out to external API's, a wait is required. I'm working on one right now in which a query is POSTed to an API, then the API returns a URL, but the actual data generated in the report at the URL could take up to three seconds. So, when they want that report, I'm using the busy loop. GG answering the actual _question_ @BeNdErR – Anthony Atkinson May 31 '16 at 09:36
  • 1
    @Samuel Tulach, editing posts to include your own software library would be considered spamming read [how not to be a spammer](http://stackoverflow.com/help/promotion) to prevent this in the future. – milo526 May 06 '17 at 15:05
  • 1
    ```function wait(ms) { const start = performance.now(); while(performance.now() - start < ms); }``` – pomber Sep 27 '17 at 21:30