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.
setTimeout
as well as setInterval
only register functions (callbacks) but then go straight to the next command.
Therefor Hi
and Hola
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 seconds setTimeout
kicks in and clears setInterval
.
The comments show the execution order
(function() { // 0 anonymous function is called inline
var i = setInterval(function() { // 1 setInterval **schedules** the function
// parameter to be executed every second
console.log(new Date());
}, 1000);
console.log("Hi"); // 2 Display 'Hi' on console
setTimeout(function() { // 3 **Schedule** the function parameter to
// execute after three seconds
clearInterval(i);
}, 3000);
console.log("Hola"); // 4 Display 'Hola' on console
})();
// 5 Display date from setInterval function
// 6 Display date from setInterval function
// 7 Display date from setInterval function
// 8 Cancel setInterval executed from
// setTimeout function
Hope this clears up your confusion.
Everything out setTimeout()
and setInterval()
is executed anyway.
It's not the sleep()
PHP's method... sadly!
However, this link could be useful: http://www.phpied.com/sleep-in-javascript/
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.