228

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

0

9 Answers 9

246

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:

Sign up to request clarification or add additional context in comments.

5 Comments

(+1) look at setTimeout() and setInterval() in javascript
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).
Good catch, Steve. I've edited my answer to reflect your comments.
ES6 will have a new operator yield which can be used to "simulate" threads. See taskjs.org for an example library.
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.
96

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:

2 Comments

this is the recommend approach in 2017
And in 2020 as well :)
94

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) {} } 

16 Comments

does exactly what it is supposed to
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.
That's a "busy wait" a.k.a you are "burning the thread"
For my unit testing purposes its useful. Surely, not for production.
This is a very bad idea.
|
11

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

1 Comment

Copying other answers is not nice
7

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.

Comments

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.

7 Comments

I want the current thread to go for waiting state for specified number of seconds
Spinning a loop cause High CPU utilization.
You should never quote the first parameter for setTimeout—pass an anonymous function or a function reference. The corrected version is: setTimeout(Func1, 3000);
(Quoting the first parameter of setTimeout invokes "eval()" unnecessarily.)
@Nick: No, if you want to pass parameters, you use a closure.
|
4

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

Comments

1

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.

Comments

-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); } 

1 Comment

setTimeout was already mentioned a looong time ago. and the rest of the code has nothing to do with the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.