What's the equivalent of Java's Thread.sleep() in Javascript?
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.
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.
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:
- http://stackoverflow.com/questions/30036/javascript-and-threads
- http://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading
And this question may also be helpful:
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.