216

What's the equivalent of Java's Thread.sleep() in JavaScript?

wonea
  • 4,783
  • 17
  • 86
  • 139
Niger
  • 3,916
  • 5
  • 30
  • 30

9 Answers9

240

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

Community
  • 1
  • 1
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
  • 1
    (+1) look at setTimeout() and setInterval() in javascript – Mahesh Velaga Sep 19 '09 at 14:42
  • 9
    To promote good coding practices, it might be best to insert a semi-colon after "500" and initialise "millisecondsToWait" in the code sample (e.g. by preceding it with "var ") (this way, if someone copies and pastes the sample, they won't end up with an implied global). – Steve Harrison Sep 20 '09 at 05:58
  • 2
    Good catch, Steve. I've edited my answer to reflect your comments. – Daniel Pryden Sep 20 '09 at 18:52
  • ES6 will have a new operator `yield` which can be used to "simulate" threads. See http://taskjs.org/ for an example library. – snorbi Sep 09 '13 at 07:27
  • Using "setTimeout" will not stop the javascript thread and wait. Its only when the call stack is empty that the counting starts. But it depends on your intention which approach you want to use. – deftextra Dec 17 '19 at 23:29
91

Try with this code. I hope it's useful for you.

function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}
David Miró
  • 2,694
  • 20
  • 20
  • 6
    does exactly what it is supposed to – maazza Jun 12 '13 at 07:56
  • 109
    This doesn't put the thread to sleep, it just consumes the thread with wasteful calculation that is likely to block the UI. Not recommended. – superdweebie Mar 30 '14 at 08:34
  • 21
    That's a "busy wait" a.k.a you are "burning the thread" – Csaba Toth Jun 12 '14 at 20:27
  • 22
    For my unit testing purposes its useful. Surely, not for production. – armandomiani Jan 28 '15 at 00:40
  • 3
    "thread.distract" – Gianthra May 16 '18 at 10:13
  • 3
    This is a very bad idea. – Alexis Dufrenoy May 15 '19 at 13:24
  • 1
    Whatever you were doing was wrong. – Dejan Nov 18 '19 at 13:36
  • It works in the same way as Thread.sleep in JAVA. Although never a good choice to implement something in production, but it answers the question perfectly. – Oscar Calderon Dec 05 '19 at 15:38
  • Complete browser tab is Hung. Not recommended solution. Please remove it. – Vikas Gupta Mar 29 '20 at 15:12
  • This is the equivalaent of ` While (CurrentTime < TimeA){ Thread.Sleep(0); } ` – Joe Apr 19 '20 at 02:53
  • Don't understand how this got so many upvotes. Don't use it. See @Richrd answer. – bruno.almeida Oct 07 '20 at 17:15
  • @bruno.almeida because it is the correct answer. Thread.Sleep() makes the thread hang for the given timeout, nothing else processes on that thread. This does the exact same thing. – Josh Feb 17 '22 at 21:37
  • @Josh It doesn't, though. `Thread.sleep()` *sleeps* a thread, consuming essentially zero resources. This is the opposite of that: the thread doesn't sleep and it burns CPU in a very tight loop. – Dave Newton Jul 21 '22 at 14:12
  • 1
    @DaveNewton yes this is true from a resource use perspective, but from a code flow execution perspective this is better than the accepted answer at simulating a thread.sleep(). Consider the case of a webworker processing its queue of messages, the accepted answer results in the worker moving on to the next message while the previous is still waiting on the timeout callback. The thread is not functionally asleep as it is handling other message. This answer actually prevents the thread from moving on to do other work. – Josh Jul 22 '22 at 15:10
  • @Josh :shrug: That sounds more like an issue with the queue consumer; if it doesn’t have a way to throttle itself and/or it isn’t callback-/promise-driven there’s already a potential problem. But this is orthogonal to the question, and my comment. Busy loops in JS are a problem because they have direct impact on system behavior. Are there isolated cases where they’re ok(-ish)? Sure. – Dave Newton Jul 22 '22 at 15:21
77

Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:

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

You can then use the sleep function in any other async function like this:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log
}

This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.

From MDN:

The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.

For a full explanation see:

Richrd
  • 6,722
  • 1
  • 17
  • 12
10

For Best solution, Use async/await statement for ecma script 2017

await can use only inside of async function

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

await sleep(10000); //this method wait for 10 sec.

Note : async / await not actualy stoped thread like Thread.sleep but simulate it

Toprak
  • 559
  • 6
  • 10
8

There's no direct equivalent, as it'd pause a webpage. However there is a setTimeout(), e.g.:

function doSomething() {
  thing = thing + 1;
  setTimeout(doSomething, 500);
}

Closure example (thanks Daniel):

function doSomething(val) {
  thing = thing + 1;
  setTimeout(function() { doSomething(val) }, 500);
}

The second argument is milliseconds before firing, you can use this for time events or waiting before performing an operation.

Edit: Updated based on comments for a cleaner result.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
5

You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:

setTimeout("Func1()", 3000);

This will call 'Func1()' after 3 seconds.

Edit:

Credit goes to the commenters, but you can pass anonymous functions to setTimeout.

setTimeout(function() {
   //Do some stuff here
}, 3000);

This is much more efficient and does not invoke javascript's eval function.

Malaxeur
  • 5,973
  • 1
  • 36
  • 34
4

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

Eranga
  • 161
  • 1
  • 2
0

Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.

The Machine
  • 1,221
  • 4
  • 14
  • 27
-1

This eventually helped me:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }
  • 5
    setTimeout was already mentioned a looong time ago. and the rest of the code has nothing to do with the question. – AbcAeffchen Aug 24 '14 at 01:29