A timer schedules JavaScript to run after a delay or repeatedly. In a custom element, setInterval(() => this.update(), 1000) updates a counter once per second, producing a simple countdown. section 4.5
Choose the scheduling mechanism according to the work being performed:
- Use setInterval for ordinary recurring updates, such as decrementing and displaying a counter every 1,000 milliseconds. section 4.5
- Use requestAnimationFrame for visual changes that should follow the browser's render cycle; call it again from each update because it runs once. section 4.5
- Store the timer handle and clear it when a component leaves the DOM, preventing updates, logging, or network work from continuing unnecessarily. section 4.3
Countdown component
A custom element initializes counter to 100, schedules update every second, writes the counter with innerHTML, and decrements it. A visual variant repeatedly schedules requestAnimationFrame, shrinks its width, and resets at zero. section 4.5
Cleaning up a removed timer
Capture the interval handle as this.timer, then clear it in disconnectedCallback with clearInterval(this.timer). Removing the element can then stop its countdown and console logging. section 4.3
Listing 4.8. A countdown timer component
<html>
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<script>
class CountdownTimer extends HTMLElement {
connectedCallback() {
this.counter = 100;
setInterval( () => #1
this.update(), 1000);
}
update() {
this.innerHTML = this.counter; #2
this.counter --; #3
}
}
customElements.define('countdown-timer', CountdownTimer);
</script>
</head>
<body>
<countdown-timer></countdown-timer>
</body>
</html>
Browse the complete countdown custom element, including interval setup, DOM output, and counter decrementing. section 4.5



