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.
setTimeoutas well assetIntervalonly register functions (callbacks) but then go straight to the next command.Therefor
HiandHolaare printed before the first callbacks are called.First callback will be that of
setIntervalafter 1 sec, then again after 2 sec.. After 3 secondssetTimeoutkicks in and clearssetInterval.