JavaScript Tutorial in Hindi #29 | Timer Functions (2025)

✅ 1. Introduction to Timer Functions

  1. Timer functions let you run code after a delay or repeatedly at intervals.
  2. Useful for animations, countdowns, alerts, and periodic tasks.

✅ 2. setTimeout() – Delay Execution

  1. Runs a function once after a specified delay (in milliseconds).
js
CopyEdit
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);

✅ 3. setInterval() – Repeat Execution

  1. Runs a function repeatedly every specified interval (in milliseconds).
js
CopyEdit
const intervalId = setInterval(() => {
console.log("Runs every 3 seconds");
}, 3000);

✅ 4. clearTimeout() & clearInterval() – Stop Timers

  1. clearTimeout(timeoutId) stops a delayed function before it runs.
  2. clearInterval(intervalId) stops repeated execution.

Example:

js
CopyEdit
const timeoutId = setTimeout(() => {
console.log("Won't run");
}, 5000);

clearTimeout(timeoutId); // Cancels above timeout

const intervalId = setInterval(() => {
console.log("Repeating...");
}, 1000);

setTimeout(() => {
clearInterval(intervalId); // Stop after 5 seconds
console.log("Interval stopped");
}, 5000);

✅ 5. Practical Examples

Countdown Timer (from 10 to 0)

js
CopyEdit
let count = 10;
const countdown = setInterval(() => {
console.log(count);
count--;
if (count < 0) {
clearInterval(countdown);
console.log("Time's up!");
}
}, 1000);

Repeated Alert Every 4 Seconds (with stop after 20 seconds)

js
CopyEdit
const alertInterval = setInterval(() => {
alert("Remember to take a break!");
}, 4000);

setTimeout(() => {
clearInterval(alertInterval);
alert("Alerts stopped.");
}, 20000);