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.

1
  • 1
    use an if statement and clearInterval. Commented Nov 24, 2014 at 20:06

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.