Javascript sleep(), will block browser, block setTimeout either

I found this Javascript sleep function here and it works in FF9, Chrome 14 (tested).

function sleep(ms) {
 ms += new Date().getTime();
 while (new Date() < ms){}

This function will block browser from doing anything, even setTimeout()

setTimeout(alert('stupid'), 1000); 
// after sleep completed, setTimeout has its turn to run. 
// The alert() will be shown after 3 seconds from /*BEGIN*/

This might be a stupid thing but sometimes you have to do stupid work and it’s required.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s