SetTimeout and SetInterval
setTimeout and setInterval are Web API functions that enable scheduling delayed or repeated execution of code.
Key concepts
setTimeout
Executes a function once after a specified delay.
setInterval
Executes a function repeatedly at specified intervals.
Step by step
How They Work:
- Both are part of Web APIs.
- They schedule tasks asynchronously, so the main thread remains non-blocking.
Examples
Using setTimeout:
setTimeout(() => {
console.log('Executed after 1 second');
}, 1000);Using setInterval:
let count = 0;
const intervalId = setInterval(() => {
console.log(`Interval count: ${++count}`);
if (count === 5) {
clearInterval(intervalId); // Stop after 5 intervals
}
}, 1000);Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus