MyiWorld
MyiWorld

Reputation: 51

Stopping a JavaScript Timer when clock reached '0'

Hello Stack Overflow Community, I have a Javascript Timer which gets its date from a MySql database, however when the timer passes the date it was supposed to go to, it starts counting into negative times. How can you set the timer to stop when the date is reached? Thankyou, Code below:

        <p>Time remaining for this weeks challenge: <span id="countdown" style="font-weight:bold;"></span></p>
    <script>
        var target_date = new Date("<?php echo $default_data['w_medal-time']; ?>").getTime();
        var days, hours, minutes, seconds;
        var countdown = document.getElementById("countdown");
        setInterval(function () {
            var current_date = new Date().getTime();
            var seconds_left = (target_date - current_date) / 1000;
            days = parseInt(seconds_left / 86400);
            seconds_left = seconds_left % 86400;
            hours = parseInt(seconds_left / 3600);
            seconds_left = seconds_left % 3600; 
            minutes = parseInt(seconds_left / 60);
            seconds = parseInt(seconds_left % 60);
            countdown.innerHTML = days + "d, " + hours + "h, "
            + minutes + "m, " + seconds + "s";  
        }, 1000);
    </script>

Thankyou for taking to time to answer.

Upvotes: 0

Views: 213

Answers (1)

Jeremy W
Jeremy W

Reputation: 1935

You can use clearInterval. Here is an example

From the site:

var myVar = setInterval(function(){myTimer()}, 1000);

function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
    clearInterval(myVar);
}

So what you want to do is set your setInterval function to a variable and then check if it is passed the time you want it to be. When it is just call clearInterval(myVar);

Upvotes: 3

Related Questions