Search code examples
javascripthtmlcountercountdown

Problem with the countdown timer JS - IF Condition


I'm new to JavaScript and this website.

I have the following code for an event timer countdown:

https://codepen.io/iraffleslowd/pen/povGNdo

My problem really is with an if condition.

setInterval(function () {
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);

Because my event does not expire at the end of the countdown, it ends approximately one hour after starting.

So can someone help me add another condition so that in the interval of that time instead of showing me Expired, it shows Live or something similar?

Thank you so much!


Solution

  • You want to manage 3 different states...

    1. Counting down until LIVE
    2. LIVE
    3. EXPIRED
    (() => {
    
        const intervalId = setInterval(() => {
    
            // update countdown timer
    
            if (distance < -(ELAPSED_GAMETIME_IN_MS)) {
                // set EXPIRED
                clearInterval(intervalId);
            }
            else if (distance < 0) {
                // set LIVE
            }
    
        }, 1000);
    
    })();
    

    EDIT Working example This example utilizes moment because it's a great utility that provides all necessary math and formatting for dates and is perfect for this scenario.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <meta http-equiv="X-UA-Compatible" content="ie=edge" />
            <title>Document</title>
        </head>
        <body>
            <div id="countdown"></div>
    
            <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
            <script>
                (() => {
                    const countdownEl = document.getElementById("countdown");
    
                    const START_DATE = moment("2020-01-22");
                    const ELAPSED_GAMETIME_IN_MS = 1000 * 60 * 60 * 2; // 2 hours in milliseconds
                    const intervalId = setInterval(() => {
                        const TIME_FROM_START = START_DATE.diff(moment());
    
                        countdownEl.innerHTML = START_DATE.fromNow(); // This could be modified to show different levels of granularity...
    
                        if (TIME_FROM_START < -ELAPSED_GAMETIME_IN_MS) {
                            countdownEl.innerHTML = "EXPIRED";
                            clearInterval(intervalId);
                        } else if (TIME_FROM_START < 0) {
                            countdownEl.innerHTML = "LIVE";
                        }
                    }, 1000);
                })();
            </script>
        </body>
    </html>