What's the equivalent of Java's Thread.sleep() in JavaScript?
JavaJavascriptJava Problem Overview
What's the equivalent of Java's Thread.sleep()
in JavaScript?
Java Solutions
Solution 1 - Java
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:
- <https://stackoverflow.com/questions/30036/javascript-and-threads>
- <https://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading>
And this question may also be helpful:
Solution 2 - Java
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) {}
}
Solution 3 - Java
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:
Solution 4 - Java
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.
Solution 5 - Java
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
Solution 6 - Java
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.
Solution 7 - Java
setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript
Solution 8 - Java
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.
Solution 9 - Java
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);
}