Posts

Showing posts with the label stack overflow

javascript sleep method

For newcomers to javascript, it might come as a surprise that there is no sleep method. Worse yet, if you search the internet, you'll find all manner of really... really bad ways to simulate this. One of my favorite "rotten tomatoes" is something like this: alert('start'); var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date Note, I borrowed this horrible example from stack overflow . If you're lucky, that example will not completely crash your browser. A much better solution is something like this: alert('start'); setTimeout(function() {alert('finish')},5000); The obvious problem is that if you truly want to simply pause for 5 seconds in the middle of a really long method, the anonymous function is not going to help you out very much.. unless you do something like this alert('start'); //lots of code var a = 'foo'; setTimeout(function(){ alert(a); ...