1

我创建了一个从 40 开始并倒计时的 javascript 计时器,但它不会在 0 处停止,我希望它在达到 0 时显示一条消息(不是警报)/将一个项目添加到数据库中,然后重新启动在 40 秒。如果您能提供任何帮助,请提前致谢:D

<html>
<head>
<script type="text/javascript">
var c=40;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c-1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
</script> 
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
</form>
<p>Click on the button above. It will count down from 40</p>
</body>
</html>
4

1 回答 1

1

您想使用 setInterval 而不是 setTimeout,因为这将根据您指定的延迟定期触发该方法。

这将在计数达到 0 时重新启动计时器:

    function timedCount() {
        document.getElementById('txt').value = c;
        c = c - 1;
        if (c == 0)
            c = 40;
    }

    function doTimer() {
        if (!timer_is_on) {
            timer_is_on = true;
            t = setInterval(function () {
                timedCount();
            }, 1000);                
        }
    }

如果要在计数达到 0 时停止计时器,请使用以下命令:

    function timedCount() {
        document.getElementById('txt').value = c;
        c = c - 1;
        if (c == 0) {
            c = 40;
            clearInterval(t); // Stops the interval
        }
    }
于 2011-02-22T14:02:06.753 回答