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, ...)
function: The code you want to execute.
delay: Time in milliseconds before execution.
arg1, arg2...: Optional parameters to pass to the function.
Example:
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);
What happens:
The message is logged once after 2 seconds.
setInterval
Purpose: Executes a function repeatedly at fixed intervals.
setInterval(function, interval, arg1, arg2, ...)
Similar structure to setTimeout, but it repeats execution.
setInterval(() => {
console.log("Hello every 1 second");
}, 1000);
What happens:
The message logs to the console every second, indefinitely (until you stop it).
Stopping Them
setTimeout returns a timeoutID that you can cancel with clearTimeout(timeoutID)
setInterval returns an intervalID that you can cancel with clearInterval(intervalID)
const intervalId = setInterval(() => {
console.log("Repeating...");
}, 1000);
setTimeout(() => {
clearInterval(intervalId);
console.log("Stopped the interval after 5 seconds");
}, 5000);