StaticFast

How to Make a JavaScript Count-Down Timer

A countdown timer is a great way to tell a visitor how many seconds remain until an event such as a wedding or a new product launch. They are used in websites ranging from personal blogs to large business sites.

In this tutorial, we will show you how to create a countdown timer using Javascript.

Create the HTML page

The first step in making a countdown timer is to build the HTML page for it. This will include a super simple DIV element, create a file index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Count Down Timer</title> </head> <body> <h1 id="timer"></h1> </body> </html>

This page contains a single HTML element h1.

Create the Javascript timer

Once the HTML is ready, you need to create the JavaScript to create a countdown timer. This can be accomplished in a few simple steps.

First, you'll need to define a function for your countdown timer. We'll call it countDown and define its properties as follows:

function countDown(ele, from) { ele.textContent = from; const timer = setTimeout(function () { if (0 === from) { clearTimeout(timer); } else { from = from - 1; ele.textContent = from; countDown(ele, from); } }, 1000) }

The function countDown accepts two parameters. The ele is the countdown timer in the page and from is which number we want it to count down from.

In this function, we are using setTimeout instead of setInterval. The reason is that when using setInterval, it does not block the execution of the script even if some exceptions happen. This might cause a memory leak.

In this function, we recursively call the function itself until the timer hits zero. And we clear the setTimeout ID at last.

secondly, we call the function countDown when the document is loaded completely:

document.addEventListener('DOMContentLoaded', function (event) { countDown(document.getElementById('timer'), 5); });

The End

The completed HTML file looks like this:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function countDown(ele, from) { ele.textContent = from; const timer = setTimeout(function () { if (0 === from) { clearTimeout(timer); } else { from = from - 1; ele.textContent = from; countDown(ele, from); } }, 1000) } document.addEventListener('DOMContentLoaded', function (event) { countDown(document.getElementById('timer'), 5); }); </script> </head> <body> <h1 id="timer"></h1> </body> </html>

You can view the result on the Codepen page at https://codepen.io/dilab/pen/mdjGZEj.

© 2024 StaticMaker. All rights reserved.