倒计时结束后如何停止计时器

How to stop timer after the the countdown is over

本文关键字:何停止 计时器 结束 倒计时      更新时间:2023-09-26
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
    setTimeout('Decrement()',1000);
}
function Decrement() {
    if (document.getElementById) {
        minutes = document.getElementById("minutes");
        seconds = document.getElementById("seconds");
        // if less than a minute remaining
        if (seconds < 59) {
            seconds.value = secs;
        } else {
            minutes.value = getminutes();
            seconds.value = getseconds();
        }
        secs--;
        setTimeout('Decrement()',1000);
    }
}
function getminutes() {
    // minutes is seconds divided by 60, rounded down
    mins = Math.floor(secs / 60);
    return mins;
}
function getseconds() {
    // take mins remaining (as seconds) away from total seconds remaining
    return secs-Math.round(mins *60);
}
</script>
</head>
<body>
<div id="timer">
    Time Left: 00:<input id="minutes" type="text" style="width: 20px; border: none; background-color:none; font-size: 16px; font-weight: bold;">:<input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;">
</div>
<script>
countdown();
</script>

在此 java 脚本代码中,计时器在时间结束并且时间进入减去示例 (00-1:30) 后执行。所以我想在计时器到达 00:00 时停止计时器。它应该在时间完成或提交页面时发出警报。

有几个问题,最大的问题是您正在测试seconds而不是seconds.value,因此您总是进入 else 块。 但是,您也没有何时达到零的条件。 这是一个应该解决这些问题的 jsfiddle,http://jsfiddle.net/psQb5/。

有两种

可能性。一种是使用 setInterval 函数而不是 setTimeout。喜欢这个。

<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var intervalVar;
function countdown() {
    intervalVar = setInterval('Decrement()',1000);
}
function Decrement() {
    if (document.getElementById) {
        minutes = document.getElementById("minutes");
        seconds = document.getElementById("seconds");
        // if less than a minute remaining
        if (seconds < 59) {
            seconds.value = secs;
        } else {
            minutes.value = getminutes();
            seconds.value = getseconds();
        }
        secs--;
        if (secs == 0) {
            window.clearTimeout(intervalVar);
            alert('timeout');
        }
    }
}
function getminutes() {
    // minutes is seconds divided by 60, rounded down
    mins = Math.floor(secs / 60);
    return mins;
}
function getseconds() {
    // take mins remaining (as seconds) away from total seconds remaining
    return secs-Math.round(mins *60);
}
</script>

使用 setInterval() 函数而不是 setTimeout()。当你想使用 clearInterval() 函数停止计时器时。

有关上述功能的基本了解,请单击下面

W3学校.