Understanding JavaScript Timers: Key Concepts and Examples
setTimeout
setInterval
setTimeout
Used to delay the execution by given time. It accepts two arguments first one is a callback function with executable statements, second is time in milliseconds.
It executes the callback only once after provided time. setTimeout
returns a timer id which can be used for clearing the timeout.
e.g.
setTimeout(() => {console.log("Hello world.")}, 4000);
// It prints console log message after 4 seconds
This can be written in other way as well
e.g.
const callbackFn = (arg) => {console.log("Hello world." + arg); // Now this is accepting a argument
setTimeout(callbackFn, 4, "some value");
// We can pass argument to callback function as third or next arguments
// It will result as "Hello world. some value"
setInterval
Used to delay the execution by given time in a loop. It accepts two arguments first one is a callback function with executable statements, second is time in milliseconds.
It executes the callback in loop periodically by given time. Note that it will execute the callback until you kill the process or manually clear (halt) the timer.
setInterval
return a timer id which can be used for clearing the interval.
setInterval(() => {console.log("Hello world.")}, 4000);
// It prints console log message after every 4 seconds, until the process or timer is cleared.
// Example with clear interval, eexecute the callbak for 5 times
let counter = 0;
const interval = setInterval(() => {
console.log("Hello world.");
counter = counter + 1;
if (counter === 5) {
clearInterval(interval)
}
}, 4000);
The clearInterval
function allows to clear or stop the setInterval function.