Sunday, March 17, 2013

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());


2 comments: