当时钟达到'0'时停止JavaScript定时器

时间:2014-11-24 20:03:45

标签: javascript php html mysql timer

Hello Stack Overflow社区, 我有一个Javascript Timer从MySql数据库获取它的日期,但是当计时器通过它应该去的日期时,它开始计入负数时间。如何在达到日期时将计时器设置为停止?谢谢你,代码如下:

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

谢谢您抽出时间回答。

1 个答案:

答案 0 :(得分:3)

您可以使用clearIntervalHere is an example

来自网站:

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

所以你想要做的是将setInterval函数设置为一个变量,然后检查它是否在你想要的时间传递。只需拨打clearInterval(myVar);

即可