The next code display the date every 1 sec and then stops.
(function() {
var i = setInterval(function() {
console.log(new Date());
}, 1000);
console.log("Hi");
setTimeout(function() {
clearInterval(i);
}, 3000);
console.log("Hola");
})();
Output:
Hi
Hola
Wed Oct 24 2012 13:35:27 GMT+0200 (CEST)
Wed Oct 24 2012 13:35:28 GMT+0200 (CEST)
Wed Oct 24 2012 13:35:29 GMT+0200 (CEST)
But I don't know why Hi
and Hola
are displayed first. Also, why setTimeout
is executed? It is not supposed that setInterval
is executed every 1 sec and nothing else can be executed?. (Does the code above runs on the order in which it is written?)
Thanks.
Everything out
setTimeout()
andsetInterval()
is executed anyway. It's not thesleep()
PHP's method... sadly!However, this link could be useful: http://www.phpied.com/sleep-in-javascript/
The comments show the execution order
Hope this clears up your confusion.
http://ejohn.org/blog/how-javascript-timers-work/
Those two events are asynchronous. They are queued/executed at the next available moment, not at the exact time "setTimeout" or "setInterval" is called.
setTimeout
as well assetInterval
only register functions (callbacks) but then go straight to the next command.Therefor
Hi
andHola
are printed before the first callbacks are called.First callback will be that of
setInterval
after 1 sec, then again after 2 sec.. After 3 secondssetTimeout
kicks in and clearssetInterval
.