Is there a way I can do a sleep in JavaScript before it carries out another action?
Example:
var a = 1+3;
// Sleep 3 seconds before the next action
If you want less clunky functions than setTimeout
and setInterval
, you can wrap them in functions that just reverse the order of the arguments and give them nice names:
function after(ms, fn){ setTimeout(fn, ms); }
function every(ms, fn){ setInterval(fn, ms); }
CoffeeScript versions:
after = (ms, fn)-> setTimeout fn, ms
every = (ms, fn)-> setInterval fn, ms
You can then use them nicely with anonymous functions:
after(1000, function(){
console.log("it's been a second");
after(1000, function(){
console.log("it's been another second");
});
});
Now it reads easily as "after N milliseconds, ..." (or "every N milliseconds, ...")