#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:

  1. Recurring Execution:
    • Continuously invokes the callback at specified intervals.
  2. Interval Timing:
    • Time between executions includes the callback's execution time.
  3. Persistence:
    • Continues until explicitly cleared or the page is closed.

Why It Matters:


How to Implement:

  1. Basic Usage:
    • const intervalId = setInterval(callback, intervalInMs);
  2. Passing Parameters:
    • setInterval(callback, intervalInMs, param1, param2, ...);
  3. Cancellation:
    • clearInterval(intervalId); to stop recurring execution.

Example:

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!'));
```


Connections:


References:

  1. Primary Source:
    • MDN Web Docs, Window.setInterval()
  2. Additional Resources:

Tags:

#JavaScript #Asynchronous #setInterval #Timing #EventLoop #PeriodicExecution


Connections:


Sources: