\n\nHere you go! This vanilla HTML and JavaScript concoction brews a 10-second countdown onto your webpage. The setInterval function clocks every second, decreasing the time and refreshing the

content. When the clock strikes zero, the timer hangs up its boots automatically.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Anton Shumikhin","url":"https://explain.codes//author/anton-shumikhin"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-12-06T13:30:01.289Z","dateModified":"2024-12-06T13:30:03.117Z"}

Explain Codes LogoExplain Codes Logo

Create a simple 10 second countdown

javascript
promises
callbacks
custom-elements
Anton ShumikhinbyAnton Shumikhin·Dec 6, 2024
TLDR
<p id="countdown">10</p> <!-- Here lives the countdown --> <script> let time = 10; // Top of the world const timer = setInterval(() => { document.getElementById('countdown').textContent = time <= 0 ? clearInterval(timer) // Bye bye, timer. You can rest now. : time--; // Another one bites the dust... }, 1000); // One Mississippi... </script>

Here you go! This vanilla HTML and JavaScript concoction brews a 10-second countdown onto your webpage. The setInterval function clocks every second, decreasing the time and refreshing the <p> content. When the clock strikes zero, the timer hangs up its boots automatically.

The stopwatch tick: SetInterval explained

The setInterval() function is our ace in the hole. It muzzle-loads the specified callback function and fires it off every 1000 milliseconds. This rhythmic trigger provides the bullet-time effect for our timer.

The bullet steps:

  1. time variable kicks the bucket by 1 when it's above zero.
  2. The DOM gets a facelift using document.getElementById().
  3. The interval rides into the sunset with clearInterval() when time is zero.

By gunning for a 1000 millisecond interval, our stopwatch audibly ticks every second. And yes, it doesn't need a wingman - no external libraries or frameworks, just good old JavaScript and HTML.

Different shades of the timer

Chalking up a completion message

Adding a countdown completion message is as easy as pie. The modified script would look something like this:

<p id="countdown">Your download will start in 10 seconds.</p> <!-- Tick-tock on the clock --> <script> let time = 10; // Initial countdown number const timer = setInterval(() => { const countdownElement = document.getElementById('countdown'); // We got you, countdown element! if(time > 0) { countdownElement.textContent = `Your download will start in ${time--} seconds.`; } else { clearInterval(timer); // Calling it a day, one could say. countdownElement.textContent = 'Downloading...'; // Let's get this show on the road! } }, 1000); </script>

Countdown as a progress bar

Ever thought of a countdown that fills up instead of ticking off? Say hello to the progress bar variant:

<progress id="countdown" value="10" max="10"></progress> <!-- Watch me grow! --> <script> let time = 10; // Here we start... const timer = setInterval(() => { const countdownElement = document.getElementById('countdown'); // Progress bar, incoming! if(time >= 0) { countdownElement.value = time--; // Look, Mom - I'm filling up! } else { clearInterval(timer); // All good things must come to an end. countdownElement.textContent = 'Countdown complete!'; // And we have liftoff... } }, 1000); </script>

Sporting the <progress> element, this gives a visual stimulus to the countdown without the need for any additional styling.

Countdown plus: Adding a zing to your timer

Kickoff on user click

Dropping the green flag with a user action, like clicking a button, amps up the game. An example:

<button id="startBtn">Start Download</button> <p id="countdown">Ready when you are!</p> <script> document.getElementById('startBtn').onclick = function() { let time = 10; // Counting down... document.getElementById('countdown').textContent = 'Starting in 10 seconds.'; const timer = setInterval(() => { const countdownElement = document.getElementById('countdown'); if(time > 0) { countdownElement.textContent = `Starting in ${time--} seconds.`; } else { clearInterval(timer); // Enough waiting around. countdownElement.textContent = 'Download initiated!'; // Fetching your records, hang tight! } }, 1000); }; </script>

Reusable timers with custom elements

Custom elements can be crafted to clone timers across your different web escapades:

<download-timer></download-timer> <script> class DownloadTimer extends HTMLElement { connectedCallback() { this.innerHTML = `<p id="countdown">10</p>`; this.startCountdown(); } startCountdown() { let time = 10; // Ready, set, go! const timer = setInterval(() => { this.querySelector('#countdown').textContent = time--; // Buckle up, countdown started! if(time < 0) { clearInterval(timer); // Don't stick around more than needed. this.textContent = 'Download ready!'; // Your wait is rewarded! } }, 1000); } } customElements.define('download-timer', DownloadTimer); // Welcome aboard, DownloadTimer! </script>

This component-based approach nestles the countdown logic within a custom HTML element. Say hello to code reusability and simplified maintenance.