
setInterval and setTimeout in JS setInterval and setTimeout are two commonly used timing functions in JavaScript that allow you to schedule code execution.
setTimeout
Purpose: Executes a function once after a delay.
Syntax:
setTimeout(function, delay, arg1, arg2, ...)Example:
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);What happens:
setInterval
Purpose: Executes a function repeatedly at fixed intervals.
setInterval(function, interval, arg1, arg2, ...)setInterval(() => {
console.log("Hello every 1 second");
}, 1000);What happens:
Stopping Them
const intervalId = setInterval(() => {
console.log("Repeating...");
}, 1000);
setTimeout(() => {
clearInterval(intervalId);
console.log("Stopped the interval after 5 seconds");
}, 5000);