⏱️ setTimeout() and setInterval()
Last Updated: 26th October 2025
JavaScript provides functions to schedule tasks and handle time-based events in the browser.
Hinglish Tip 🗣: Ye functions aise samjho — alarm ya timer jaise tools jo kuch kaam future me ya repeat karne ke liye set karte hain.
🕐 1. setTimeout()
- Purpose: Execute a function once after a specified delay (in milliseconds).
- Syntax:
setTimeout(function, delay, arg1, arg2, ...);
Parameters:
-
function → Function to execute
-
delay → Time in milliseconds
-
arg1, arg2,... → Optional arguments for the function
-
Example:
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);
🕐 2. setInterval()
- Purpose: Execute a function repeatedly at a specified interval (in milliseconds).
- Syntax:
setInterval(function, interval, arg1, arg2, ...);
Parameters:
-
function → Function to execute
-
interval → Time in milliseconds between each call
-
arg1, arg2,... → Optional arguments for the function
-
Example:
let count = 0;
let intervalId = setInterval(() => {
console.log("Count:", count);
count++;
if (count > 4) clearInterval(intervalId); // Stop after 5 times
}, 1000);
💡 Note:
setInterval()returns an identifier that can be used to stop the interval.
3. Clearing Timers
Stop setTimeout or setInterval using clearTimeout or clearInterval.
let timerId = setTimeout(() => console.log("Won't run"), 5000);
clearTimeout(timerId); // Cancels the timeout
let intervalId = setInterval(() => console.log("Repeating"), 1000);
clearInterval(intervalId); // Stops interval immediately
💡 Quick Practice
- Use setTimeout to log "Welcome!" after 3 seconds.
- Use setInterval to log numbers from 1 to 5 every second, then stop.
- Create a timer using setTimeout and cancel it before it executes.