Skip to content Skip to sidebar Skip to footer

Javascript Setinterval And Settimeout

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');

Solution 1:

The comments show the execution order

(function() {                           // 0 anonymous function is called inlinevar i = setInterval(function() {    // 1 setInterval **schedules** the function //     parameter to be executed every secondconsole.log(newDate()); 
    }, 1000);
    console.log("Hi");                  // 2 Display 'Hi' on consolesetTimeout(function() {             // 3 **Schedule** the function parameter to //     execute after three secondsclearInterval(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.

Solution 2:

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.

Solution 3:

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/

Solution 4:

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.

Post a Comment for "Javascript Setinterval And Settimeout"