JavaScript Timers: setTimeout() vs setInterval()
JavaScript Timers for Beginners
1. setTimeout() - Run code once after a delay
Use this when you want to delay a task.
Example:
setTimeout(() => {
console.log("Hello after 3 seconds");
}, 3000);
What it does:
- Waits 3 seconds
- Then runs the function once
2. setInterval() - Run code repeatedly
Use this when you want to repeat something every few seconds.
Example:
setInterval(() => {
console.log("Repeating every 2 seconds");
}, 2000);
What it does:
- Runs the function
- Again and again, every 2 seconds
@the_coder_dex
JavaScript Timers: setTimeout() vs setInterval()
How to stop them?
const timer = setTimeout(() => {}, 5000);
clearTimeout(timer); // Cancels setTimeout
const interval = setInterval(() => {}, 1000);
clearInterval(interval); // Cancels setInterval
Real-life uses:
- setTimeout: Show a message after a delay
- setInterval: Countdown timers, clocks, animations
Quick Tip:
setTimeout = "do it later"
setInterval = "keep doing it"
@the_coder_dex