Search code examples
javascripthtmltimercrashcountdown

Trying to fix a countdown timer issue which causes timer to run and then crash about ten seconds in using Javascript


I am having a JavaScript Issue regarding a countdown timer I am trying to implement. I know I am pretty close as a) the timer actually shows up on my screen with the correct time and b) actually starts the countdown process every second. I still consider myself to be somewhat of a novice in JavaScript so I apologise if the answer is blatantly obvious. The issue that I am having is that after about ten to fifteen seconds the countdown timer stops for a few seconds and then causes my browser to crash. If anyone has any idea as to how to prevent this and get the timer working smoothly that would be greatly appreciated.

Thank you.

Here is the JavaScript and HTML I am using in my code:

<script type="text/javascript"> 

            var endtime = new Date("October 01 2016 12:00:00");  /* DESIRED START DATE AND TIME OF EVENT */

            function getTimeLeft() {
                var now = new Date();
                var timeDiff = endtime.getTime() - now.getTime();
                if (timeDiff <=0) { /* When Countdown Reaches 00:00:00 */
                    clearTimeout(timer);
                    var inprogress = document.getElementById('countdown');
                    var inner = document.getElementsByClassName('duration, duration_number');
                    inprogress.innerHTML = "TIME IN!";
                    inner.removeClass('duration');
                    inner.removeClass('duration_number');
                    inner.addClass('gameon'); /* style this to center a big message */
                    inner.addClass('colourchanger');
                    /*document.getElementById('countdown').innerHTML = "GAME OVER!"; Checking if date has passed time out */
                }

                var seconds = Math.floor(timeDiff/1000);
                var minutes = Math.floor(seconds/60);
                var hours = Math.floor(minutes/60);
                var days = Math.floor(hours/24);

                seconds %= 60;
                minutes %= 60;
                hours %= 24;
                seconds = ("0" + seconds).slice(-2);
                minutes = ("0" + minutes).slice(-2);
                hours = ("0" + hours).slice(-2);
                //var timeinterval = setInterval(getTimeLeft,1000);
                //var timeinterval = setInterval(updateClock,1000);
                /*updateClock(); // run function again to loop every second*/
                function updateClock(){
                    if (timeDiff >0){
                    document.getElementById("daysBox").innerHTML = days;
                    document.getElementById("hoursBox").innerHTML = hours;
                    document.getElementById("minutesBox").innerHTML = minutes;
                    document.getElementById("secondsBox").innerHTML = seconds;
                    var timeinterval = setInterval(getTimeLeft,1000);
                    //setInterval(getTimeLeft,1000);
                    /*getTimeLeft();*/
                    }
                    else if(timeDiff<=0){
                        clearInterval(timeinterval);
                    }

                }
                updateClock(); // run function again to loop every second   */
            //  timeinterval(getTimeLeft,1000);
            }

        </script>

<div id="countdown" class="borderchange">
            <div class="duration">
                Days:<br><br> 
                <div class="duration_number"><span id="daysBox" class="days"></span></div>
            </div>
            <div class="duration">
                Hours:<br><br> 
                <div class="duration_number"><span id="hoursBox" class="hours"></span></div>
            </div>
            <div class="duration">
                Minutes:<br><br> 
                <div class="duration_number"><span id="minutesBox" class="minutes"></span></div>
            </div>
            <div class="duration">
                Seconds:<br><br> 
                <div class="duration_number"><span id="secondsBox" class="seconds"></span></div>
            </div>
        </div>
        <script>
        getTimeLeft();
        //setInterval(getTimeLeft,1000);
        </script>

Solution

  • You are confusion setTimeoutwith setInterval. From W3Schools:

    The two key methods to use with JavaScript are:

    • setTimeout(function, milliseconds)

      Executes a function, after waiting a specified number of milliseconds.

    • setInterval(function, milliseconds)

      Same as setTimeout(), but repeats the execution of the function continuously.

    You are calling setInterval(getTimeLeft,1000); each time getTimeLeft is called, so after 2 seconds there are already 4 intervals running doing the same, after 3 second 8 and so on.

    Delete the line setInterval(getTimeLeft,1000); in your updateClock() function and uncomment the line setInterval(getTimeLeft,1000); in the last line in your HTML-part to start the interval only once.

    Also, to clear it properly, you should save this interval into a global var so you can then reference it in updateClock().

    Fiddle