What's the equivalent of Java's Thread.sleep() in JavaScript?
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:
- JavaScript and Threads
- Why doesn't JavaScript support multithreading?
And this question may also be helpful:
- setTimeout - how to avoid using string for callback?
What is the JavaScript version of sleep()?
2017 — 2021 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));
}
Or as a one-liner:
await new Promise(r => setTimeout(r, 2000));
As a function:
const sleep = ms => new Promise(r => setTimeout(r, ms));
or in Typescript:
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
use it as:
await sleep(<duration>);
Demo:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}
demo();
How to call Thread.sleep within Nashorn JS Script
It seemed to work for me with this code
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByExtension("js");
int time_in_ms = 3000;
se.put("ms", time_in_ms);
Instant before = Instant.now();
se.eval("java.lang.Thread.sleep(ms)");
Instant after = Instant.now();
System.out.printf("Expected: %dms Actual %dms%n", time_in_ms, Duration.between(before, after).toMillis());
I could alter time_in_ms
and get different values, e.g.
Expected: 3000ms Actual 3195ms
(obviously they are different because of the overhead of eval-ing the javascript)
I tried under Windows with JDK1.8 and JDK11.
Is there a sleep function in JavaScript?
You can use the setTimeout
or setInterval
functions.
What is the equivalent of javascript setTimeout in Java?
"I used the Timer class, but I think that that is not the best way."
The other answers assume you are not using Swing for your user interface (button).
If you are using Swing then do not use Thread.sleep()
as it will freeze your Swing application.
Instead you should use a javax.swing.Timer
.
See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.
Difference between wait() vs sleep() in Java
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
Yet another point is that you can get spurious wakeups from wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
What is the JavaScript version of sleep()?
2017 — 2021 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));
}
Or as a one-liner:
await new Promise(r => setTimeout(r, 2000));
As a function:
const sleep = ms => new Promise(r => setTimeout(r, ms));
or in Typescript:
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
use it as:
await sleep(<duration>);
Demo:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}
demo();
JavaScript sleep/wait before continuing
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.
Related Topics
What Is the Equivalent of a Java Hashmap<String,Integer> in Swift
Java Equivalent to JavaScript's Encodeuricomponent That Produces Identical Output
Alternative to Jzebra/Qz Java Raw Print Plugin After Npapi Being Dropped on Chrome Browser
Calling a Java Servlet from JavaScript
Leaking This in Constructor Warning
Environment Variables in Eclipse
Java: Literal Percent Sign in Printf Statement
How to Install Various Python Libraries in Jython
Spark Error - Unsupported Class File Major Version
Jackson Serialization: Ignore Empty Values (Or Null)
Authenticated Http Proxy with Java
Reading a .Txt File Using Scanner Class in Java
Builder Pattern in Effective Java
Why Would One Declare an Immutable Class Final in Java
Stack Overflows from Deep Recursion in Java
How to Get Country Phone Prefix from Iso
Manifest Merger Failed:Uses-Sdk:Minsdkversion 8 Cannot Be Smaller