• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • VBA
  • About
You are here: Home / JavaScript / How to Create a JavaScript Countdown Timer

How to Create a JavaScript Countdown Timer

February 28, 2022 1 Comment

In JavaScript, we can make a countdown timer somewhat easily with the help of the setTimeout and setInterval methods.

setTimeout(function(){
  //Code that will run after 5000 milliseconds
}, 5000);
setInterval(function(){
  //Code that will run every 1000 milliseconds
}, 1000);

You can see in the code above that the setTimeout() method will run the function after 5000 milliseconds. We can change that parameter to be however long we want to wait to execute the function call.

On the other hand, the setInterval() method will run the function every 1000 milliseconds. We can change that parameter to be however often we want to execute the function call.


Let’s say we want to run code that executes an alert box after 10 seconds. We can do this easily using the setTimeout method.

Here is the JavaScript code that can make this happen.

setTimeout(function(){
  alert("10 seconds have passed.")
}, 10000);

Let’s take a look at another example below.

Creating a JavaScript Countdown Timer Using the setTimeout() and setInterval() Methods

In this example, we will use the setTimeout() method to create a simple countdown timer that will display a message when finished. It will start when the user presses a button. We will also let the user enter the number of seconds they want the countdown timer to run for.

Here is the simple HTML setup:

<div id="div1">
  <p>How many seconds would you like the countdown timer to start from?</p>
  <input id="userInput" type="number">
  <div id="click-me" onclick="startCountdown()">Start Countdown</div>
  <div id="countdown-text"></div>
</div>

To make this countdown timer happen, we will use the setTimeout() method and the setInterval() method. We will first get the number of seconds the user has entered into the input field using the value property. We will use this as our start number for the timer.

Once we have the seconds the user has given us, we will multiply that number by 1000 to convert it to milliseconds. We will then use that as our milliseconds parameter for the setTimeout() method.

While the setTimeout() method is waiting to execute its function call, we will provide the user with a countdown by using the setInterval() method. The setInterval() method will run every second until it is told to stop.

Inside the setInterval() method, we will run a function that runs every second. The function will display how many seconds remain in the countdown timer. We will use the innerHTML property to update the text for the user.

We will end the setInverval() method using the clearInterval() method when our counter has reached 0.

Finally, in our setTimeout() method we will have an alert box alert the user when the countdown timer is done. We will also add some code to make it so the user can’t run the countdown timer again until it has completed its cycle.

Here is the JavaScript code:

//The variable below will just make it so the user cannot run the setTimeout method more than once at a time
var isSetTimmeoutRunning = false;
  
function startCountdown(){

  if( isSetTimmeoutRunning == false ){
    //We set this variable to true when we first run the setTimeout method.
    //It will get set back to false when the setTimeout method has completed
    isSetTimmeoutRunning = true;
    
    //Get the seconds the user has given us
    var userInput = Number(document.getElementById("userInput").value);

    //Next, we will convert the seconds to milliseconds
    var userMilliseconds = userInput*1000;
    
    setTimeout(function(){
      isSetTimmeoutRunning = false;
      //Send alert message to the user
      alert(userInput + " seconds have passed.");
    }, userMilliseconds);
    
    //The initial starting point of the counter is the user inputted seconds
    var counter = userInput;
    
    document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";

    var interval = setInterval(function(){
      counter--;
      document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";
      if( counter == 0 ){
        document.getElementById("countdown-text").innerHTML = "";
        clearInterval(interval);
      }
    }, 1000);
  }
}

The final code and output for this example of how to create a JavaScript countdown timer is below:

Code Output:

How many seconds would you like the countdown timer to start from?

Start Countdown

Full Code:

<div id="div1">
  <p>How many seconds would you like the countdown timer to start from?</p>
  <input id="userInput" type="number">
  <div id="click-me" onclick="startCountdown()">Start Countdown</div>
  <div id="countdown-text"></div>
</div>

<script>

var isSetTimmeoutRunning = false;  
function startCountdown(){
  if( isSetTimmeoutRunning == false ){
    isSetTimmeoutRunning = true;
    var userInput = Number(document.getElementById("userInput").value);
    var userMilliseconds = userInput*1000;
    setTimeout(function(){
      isSetTimmeoutRunning = false;
      alert(userInput + " seconds have passed.");
    }, userMilliseconds);
    var counter = userInput;
    document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";
    var interval = setInterval(function(){
      counter--;
      document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";
      if( counter == 0 ){
        document.getElementById("countdown-text").innerHTML = "";
        clearInterval(interval);
      }
    }, 1000);
  }
}

</script>

Hopefully this article has been useful for you to understand how to create a JavaScript countdown timer.

Other Articles You'll Also Like:

  • 1.  Changing the Background Image of a div in JavaScript
  • 2.  Using JavaScript to Get the Page Title
  • 3.  JavaScript tan – Find Tangent of Number in Radians Using Math.tan()
  • 4.  Using Javascript to Remove Class from Element
  • 5.  Set the Height of a Div Using JavaScript
  • 6.  How to Find the Longest String in an Array in JavaScript
  • 7.  JavaScript Coin Flip – How to Simulate Flipping a Coin in JavaScript
  • 8.  JavaScript cos – Find Cosine of Number in Radians Using Math.cos()
  • 9.  Using JavaScript to Check if Variable is a Number
  • 10.  Using JavaScript to Show a Div

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Comments

  1. David Aalu says

    July 30, 2022 at 1:41 pm

    cool code helped me in creating a timer for a game I’m building only bug is it allows the input of zero and negative numbers and then it won’t stop counting down

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

The Programming Expert is a compilation of hundreds of code snippets to help you find solutions to your problems in Python, JavaScript, PHP, HTML, SAS, and more.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2022 · The Programming Expert · About · Privacy Policy