How do you program a timer in javascript?

Example: Create a Countdown Timer

// program to create a countdown timer

// time to countdown from (in milliseconds)
let countDownDate = new Date().getTime() + 24 * 60 * 60 * 1000;

// countdown timer
let x = setInterval(function() {

    // get today's date and time in milliseconds
    let now = new Date().getTime();

    // find the interval between now and the countdown time
    let timeLeft = countDownDate - now;

    // time calculations for days, hours, minutes and seconds
    const days = Math.floor( timeLeft/(1000*60*60*24) );
    const hours = Math.floor( (timeLeft/(1000*60*60)) % 24 );
    const minutes = Math.floor( (timeLeft/1000/60) % 60 );
    const seconds = Math.floor( (timeLeft/1000) % 60 );

    // display the result in the element with id="demo"
    console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");

    // clearing countdown when complete
    if (timeLeft < 0) {
        clearInterval(x);
        console.log('CountDown Finished');
    }
    }, 2000);

Output

0d 23h 59m 57s 
0d 23h 59m 55s 
0d 23h 59m 53s 
0d 23h 59m 51s 
...

In the above program, the setInterval() method is used to create a timer.

The setInterval() method is executed at a given interval time (here, 2000 milliseconds).

The new Date() gives the current date and time. For example,

let d1 = new Date();
console.log(time); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)

The getTime() method returns the number of milliseconds from midnight of January 1, 1970 (EcmaScript epoch) to the specified date (here, current date).

The following code gives the next day's time in milliseconds.

new Date().getTime() + 24 * 60 * 60 * 1000;

Now, we can calculate time left using the following formula:

let timeLeft = countDownDate - now;

The remaining number of day is calculated using:

  • The time interval is divided by 1000 to determine the number of seconds, i.e. timeLeft / 1000
  • The time interval then is divided by 60 * 60 * 24 to determine the number of days remaining.
  • The Math.floor() function is used to round the number to a whole number.

Similar methods are used for hours, minutes, and seconds.


Note: You can also use a custom starting countdown time by passing a specific date.

For example,

let countDownDate = new Date("Aug 5, 2025 14:22:36").getTime();

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    A countdown timer is an accurate timer that can be used for a website or blog to display the count down to any special event, such as a birthday or anniversary.
    Basics of a countdown timer are :

    1. Set a valid end date.
    2. Calculate the time remaining.
    3. Convert the time to a usable format.
    4. Output the clock data as a reusable object.
    5. Display the clock on the page, and stop the clock when it reaches zero.

    Step 1 : Set a Valid End Date
    The Valid end date and time should be a string in any of the formats understood by JavaScript’s Date.parse() method.

    How do you program a timer in javascript?

    Step 2 : Calculate Remaining Time
    First we calculate the time remaining by subtracting the deadline by current date and time then we calculate the number of days,hours,minutes and seconds.The Math.floor() function is used to return the largest integer less than or equal to a given number.

    How do you program a timer in javascript?

    Step 3 : Output the result
    In the code below the result is given as output by id=”demo”

    How do you program a timer in javascript?

    Step 4 : Write some text if the countdown is over
    If the countdown timer is over then “expired” will be displayed on the screen.

    How do you program a timer in javascript?

    INPUT :

    <!DOCTYPE HTML>

    <html>

    <head>

    <style>

    p {

      text-align: center;

      font-size: 60px;

    }

    </style>

    </head>

    <body>

    <p id="demo"></p>

    <script>

    var deadline = new Date("Jan 5, 2018 15:37:25").getTime();

    var x = setInterval(function() {

    var now = new Date().getTime();

    var t = deadline - now;

    var days = Math.floor(t / (1000 * 60 * 60 * 24));

    var hours = Math.floor((t%(1000 * 60 * 60 * 24))/(1000 * 60 * 60));

    var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));

    var seconds = Math.floor((t % (1000 * 60)) / 1000);

    document.getElementById("demo").innerHTML = days + "d " 

    + hours + "h " + minutes + "m " + seconds + "s ";

        if (t < 0) {

            clearInterval(x);

            document.getElementById("demo").innerHTML = "EXPIRED";

        }

    }, 1000);

    </script>

    </body>

    </html>


    How do you program a timer in javascript?


    When the countdown is over
    How do you program a timer in javascript?

    Countdown Timer with CSS using JavaScript
    INPUT:

    <!DOCTYPE HTML>

    <html>

    <head>

    <style>

    body{

        text-align: center;

        background: #00ECB9;

      font-family: sans-serif;

      font-weight: 100;

    }

    h2{

      color: #396;

      font-weight: 100;

      font-size: 40px;

      margin: 40px 0px 20px;

    }

     #clockdiv{

        font-family: sans-serif;

        color: #fff;

        display: inline-block;

        font-weight: 100;

        text-align: center;

        font-size: 30px;

    }

    #clockdiv > div{

        padding: 10px;

        border-radius: 3px;

        background: #00BF96;

        display: inline-block;

    }

    #clockdiv div > span{

        padding: 15px;

        border-radius: 3px;

        background: #00816A;

        display: inline-block;

    }

    smalltext{

        padding-top: 5px;

        font-size: 16px;

    }

    </style>

    </head>

    <body>

    <h2>Countdown Clock</h2>

    <div id="clockdiv">

      <div>

        <span class="days" id="day"></span>

        <div class="smalltext">Days</div>

      </div>

      <div>

        <span class="hours" id="hour"></span>

        <div class="smalltext">Hours</div>

      </div>

      <div>

        <span class="minutes" id="minute"></span>

        <div class="smalltext">Minutes</div>

      </div>

      <div>

        <span class="seconds" id="second"></span>

        <div class="smalltext">Seconds</div>

      </div>

    </div>

    <p id="demo"></p>

    <script>

    var deadline = new Date("dec 31, 2017 15:37:25").getTime();

    var x = setInterval(function() {

    var now = new Date().getTime();

    var t = deadline - now;

    var days = Math.floor(t / (1000 * 60 * 60 * 24));

    var hours = Math.floor((t%(1000 * 60 * 60 * 24))/(1000 * 60 * 60));

    var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));

    var seconds = Math.floor((t % (1000 * 60)) / 1000);

    document.getElementById("day").innerHTML =days ;

    document.getElementById("hour").innerHTML =hours;

    document.getElementById("minute").innerHTML = minutes; 

    document.getElementById("second").innerHTML =seconds; 

    if (t < 0) {

            clearInterval(x);

            document.getElementById("demo").innerHTML = "TIME UP";

            document.getElementById("day").innerHTML ='0';

            document.getElementById("hour").innerHTML ='0';

            document.getElementById("minute").innerHTML ='0'

            document.getElementById("second").innerHTML = '0'; }

    }, 1000);

    </script>

    </body>

    </html>

    OUTPUT :

    How do you program a timer in javascript?


    When the Countdown Timer session is exceeded,the following output would be displayed:
    How do you program a timer in javascript?

    Applications of Countdown Timer

    • Used during Events to display the time left for its commencement.
    • Used by online commerce websites to display time left for an ongoing sale.
    • Used by websites during promotions
    • Used in Car racing games,football games etc
    • Used in Auction Websites to display the left for placing bids.

    Benefits of making a countdown timer in JavaScript than using plugins

    • The code will be lightweight because it will have zero dependencies.
    • The website will perform better because there won’t be any need of loading external scripts and style sheets.
    • The user gets more control because he has built the clock to behave exactly the way he wants it to rather than trying to bend a plugin according to his will.

    This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


    Is there a timer function in JavaScript?

    There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.

    How do I make a countdown timer?

    To create and manage countdown timers, open the Optimizely Campaign menu and select More > Countdown Timer..
    Select a countdown timer and click Copy..
    Optional: Edit the countdown timer as described under Creating a countdown timer, and give it a new name..
    Click Save..

    How can I add a timer to my website?

    Adding Your Timer.
    Add New Section..
    Select 'App Store & HTML'. This adds the 'Embed an App' section on your site..
    Click to Explore the App Store..
    Select 'HTML'.
    Copy and paste the code in the section provided. You may need to tick 'show in iframe' just below where you paste it if the formatting doesn't look right..

    How do you end a timer in JavaScript?

    Clicking the Stop button clears the timer by using the clearInterval(), passing in the 'check' variable that is returned by the call to setInterval().