Archive for January, 2010

sleep() function in JavaScript

Wednesday, January 6th, 2010

JavaScript doesn't have a handy sleep() or wait() or delay() function to pause the execution for a few seconds, so we can use setTimeout() function to emulate such behaviour. It's not straightforward and may require you to refactor the workflow, but it's delaying the execution and is really simple:

JAVASCRIPT:

  1. setTimeout(start, 1000);
  2.     var i = 0;
  3.    
  4.     function start() {
  5.         console.log('i am here ' + i);
  6.         i++;
  7.         setTimeout(start, 1000);
  8.     }