Javascript sleep implementation

Javascript does not have any sleep function. At times (e.g. to simulate a specific situation) we may need to sleep or delay the code for few seconds. Here is sample code which implements sleep by doing doing nothing in while loop. Using such approach should be avoided in production environment.

<div id="msg"></div>
<script type="text/javascript">
function sleep(duration) {
  var start = new Date().getTime();
  while(new Date().getTime() < start + duration){}
}
document.querySelector("#msg").innerHTML += "Time (milliseconds): " + new Date().getTime() + "<br/>";
sleep(1000);
document.querySelector("#msg").innerHTML += "After 1000 milliseconds<br/>"
document.querySelector("#msg").innerHTML += "Time (milliseconds): " + new Date().getTime() + "<br/>";
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments