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:
-
setTimeout(start, 1000);
-
var i = 0;
-
-
function start() {
-
console.log('i am here ' + i);
-
i++;
-
setTimeout(start, 1000);
-
}
April 15th, 2010 at 1:46 am
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).