setTimeout and setInterval
console.log("Start");
// setTimeout runs a function once after a specified delay (in milliseconds).
// setTimeout(callback, delay, arg1, arg2, ...);
// callback → function to execute
// delay → time in milliseconds before execution
// arg1, arg2... → optional arguments passed to the callback
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
console.log("End");
const timerId = setTimeout(() => console.log("Won't run"), 5000);
clearTimeout(timerId); // prevents execution
// setInterval runs a function repeatedly at a fixed time interval.
// setInterval(callback, interval, arg1, arg2, ...);
// interval → time in milliseconds between executions
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log("Count:", count);
if (count === 5) {
clearInterval(intervalId); // stop after 5 executions
}
}, 1000);
// Always clear intervals/timeouts if they are no longer needed, especially in React components:
useEffect(() => {
const intervalId = setInterval(() => console.log("Tick"), 1000);
return () => clearInterval(intervalId);
}, []);