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 < 5000); alert('finish');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); //lots more code },5000);If you find this solution lacking, you're probably due for some refactoring of your code as you are probably writing highly procedural code and it's likely that javascript is going to cause you other, more serious problems. This is on stack overflow here, upvote if you think it's a good solution.
Comments