How to pause execution of javascript for sometime

Today, I was just looking into the ways to pause or wait or delay execution of my javascript statement for some given time. I do some google for this and I got such a really good code snippet – sleep() function from somewhere.

sleep() Function in Javascript

function sleep(milliseconds) { 
        var start = new Date().getTime(); 
        for (var i = 0; i < 1e7; i++) { 
                if ((new Date().getTime() - start) > milliseconds){ break; } 
        } 
}

Usage

//Sleep for 1 second (1000 milliseconds). 
console.log(new Date()); 
console.log('Dude!'); 
sleep(1000); 
console.log(new Date());

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s