Discover JavaScript Timers
Timers in Bnlang allow scheduling code to run later or repeatedly.
The two most common functions are setTimeout (run once after a delay) and setInterval (run repeatedly with a fixed delay).
Timers are essential for animations, retries, scheduled updates, and asynchronous operations.
setTimeout
setTimeout runs code once after the specified delay (in milliseconds).
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);
setInterval
setInterval runs code repeatedly at the specified interval (in milliseconds). Use clearInterval to stop it.
let count = 0;
const timer = setInterval(() => {
count++;
console.log("Tick", count);
if (count === 5) clearInterval(timer);
}, 1000);
Clearing Timers
- Use
clearTimeout(timerId)to cancel a timeout. - Use
clearInterval(intervalId)to cancel an interval.
Always clear timers when they are no longer needed to avoid memory leaks.
Best Practices
- Avoid unnecessary timers; prefer event-driven code when possible.
- Always clear intervals and timeouts that you set.
- Be mindful of long-running timers in background tasks.