setTimeout() runs a function after some time runs a function after the current code has finished
function sayHi() { alert('Hello');}
setTimeout(sayHi, 1000);
// or
setTimeout(() => alert('Hello'), 1000);
// but not
setTimeout(sayHi(), 1000); // wrong! // Pass a function, but don’t run it
Pass parameters
function sayHi(phrase, who) {
alert( phrase + ', ' + who );
}
setTimeout(sayHi, 1000, "Hello", "John"); // pass params as 3rd arg
No delay setTimeout() adds function to the end of a call stack Function is scheduled to run “right after” the current script HTML5 standard says: “after five nested timers, the interval is forced to be at least 4 milliseconds” For server-side JavaScript, that limitation does not exist Function will be executed after the render Big task can be split into sub-tasks scheduled by setTimeout() and UI will be responsive we will see updates
const func = () => console.log('I am function')
func();
setTimeout(() => console.log('I am console'))
func();
// I am function
// I am function
// I am console
Canceling with clearTimeout
let timerId = setTimeout(() => alert("never happens"), 1000);
clearTimeout(timerId);
setInterval() run a function regularly, starting after the interval same syntax as setTimeout() call clearInterval(timerId) to stop further calls
// repeat with the interval of 2 seconds
let timerId = setInterval(() => alert('tick'), 2000);
// after 5 seconds stop
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);
Nested setTimeout() Similar to setInterval() More flexible Allows to set the delay more precisely Guarantees the fixed delay, but setInterval() doesn't
let timerId = setTimeout(function tick() {
alert('tick');
timerId = setTimeout(tick, 2000);
}, 2000);
Garbage collection A function references the outer lexical environment While timeout/interval live, lexical environment lives and outer variables live too They may take much more memory than the function itself Thus when we don’t need the scheduled function anymore, better to cancel it