sleep() function in JavaScript

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.     }

One Response to “sleep() function in JavaScript”

  1. qqrq Says:

    Note that this code works only within a browser (as setTimeout is window's object method), so you need DOM to do this. I knwo that using JS not with browser is very rare, but it happens (i.e. you can use it as sort of command line script in windows with JScript).

Leave a Reply