There is no sleep()/wait() function in Javascript. The setTimeout() is not exactly a sleep()/wait() function as it behaves like creating another thread for the scheduled task.
By Google, i got a manual sleep()/wait() function. Try the following code.
*Update @ 2011-07-22: This function drains CPU usage and may throw error in IE. Use with extreme caution. Thanks SmartCoder for pointing out the issue. =)
<html> <head> <script type="text/javascript"> /** * Delay for a number of milliseconds */ function sleep(delay) { var start = new Date().getTime(); while (new Date().getTime() < start + delay); } </script> </head> <body> <h1>Eureka!</h1> <script type="text/javascript"> alert("Wait for 5 seconds."); sleep(5000) alert("5 seconds passed."); </script> </body> </html>
Done =)
Reference: JavaScript Sleep Function
This is not good practice, as it will drain cpu usage, and cause IE to throw errors if longer than 5 seconds.
LikeLike
That’s true. i have added a reminder on the post. Thanks for pointing out the problem. =)
LikeLike
Here’s a possible alternative that may work in some cases:
LikeLike
It could also be done like this:
LikeLiked by 3 people
Thanks for your code. =)
LikeLike
On the function something is missing, its the var Delay = 5000…
LikeLike
Yes for better coding practice instead of hard coded it. thanks for your comment. =)
LikeLike
Hi,
If you need sleep function – you can send sync request to server …
function sleep(milliseconds) {
//code here for you SYNC request to server /*asp.net or php*/
}
it’s works,browser block all events until http response.
LikeLike
Thanks for your suggestion. =)
LikeLike
Test
LikeLike
what is your test for?
LikeLike