#atom
setInterval - Executing Code Repeatedly at Fixed Time Intervals
Core Idea:
The setInterval function schedules a callback function to execute repeatedly at specified time intervals, providing a mechanism for periodic actions without manually scheduling recurring callbacks.
Key Principles:
- Recurring Execution:
- Continuously invokes the callback at specified intervals.
- Interval Timing:
- Time between executions includes the callback's execution time.
- Persistence:
- Continues until explicitly cleared or the page is closed.
Why It Matters:
- Periodic Updates:
- Enables regularly refreshing data or UI elements.
- Animation:
- Can create time-based animations (though requestAnimationFrame is preferred).
- Polling:
- Allows checking for updates or changes at regular intervals.
How to Implement:
- Basic Usage:
const intervalId = setInterval(callback, intervalInMs);
- Passing Parameters:
setInterval(callback, intervalInMs, param1, param2, ...);
- Cancellation:
clearInterval(intervalId);
to stop recurring execution.
Example:
-
Scenario:
- Creating a countdown timer that updates every second.
-
Application:
function createCountdown(seconds, onComplete) {
let remainingSeconds = seconds;
const displayElement = document.getElementById('countdown');
updateDisplay(); // Initial display
const intervalId = setInterval(() => {
remainingSeconds -= 1;
updateDisplay();
if (remainingSeconds <= 0) {
clearInterval(intervalId);
onComplete();
}
}, 1000);
function updateDisplay() {
const minutes = Math.floor(remainingSeconds / 60);
const seconds = remainingSeconds % 60;
displayElement.textContent = ${minutes}:${seconds.toString().padStart(2, '0')}
;
}
return {
cancel: () => clearInterval(intervalId)
};
}
const timer = createCountdown(60, () => alert('Time is up!'));
```
- Result:
- Countdown timer displays and updates every second until it reaches zero.
Connections:
- Related JavaScript Concepts:
- setTimeout: For one-time delayed execution.
- requestAnimationFrame: Better alternative for visual animations.
- Broader Programming Concepts:
- Polling: Checking for updates at regular intervals.
- Time-based Programming: Coordinating actions over time.
References:
- Primary Source:
- MDN Web Docs, Window.setInterval()
- Additional Resources:
Tags:
#JavaScript #Asynchronous #setInterval #Timing #EventLoop #PeriodicExecution
Connections:
Sources:
- From: AG Grid