Javascript倒计时在每次运行后都会变得更快

Javascript countdown is getting faster after each run

本文关键字:倒计时 运行 Javascript      更新时间:2023-09-26
var i = 3400;
function progress() {
    i = 34000;
    window.setInterval(function () {
        i = i - 100;
        document.getElementById("progress").firstChild.data = i;
    }, 100);
}

这段代码越来越快了。函数进度每 3 秒调用一次,但我无法更改调用它,因为它是基于事件的。大约 10 个电话后,我变得消极!

嗯....

请勿使用setInterval

您可能想使用setTimeout

由于每 3 秒调用一次进度,因此您需要避免它重复创建新的间隔。使用 clearTimeout 会在您调用进度时重置计时器。但是,如果不知道您究竟想要实现什么,就很难提供准确的答案。

var timeout;
function counter(count) {
    document.getElementById("progress").firstChild.data = count;
    if (count >= 0) {
        timeout = window.setTimeout(function() {
            counter(count-100);
        }, 100);
    }
}
function progress() {
    window.clearTimeout(timeout);
    counter(3400);
}

试试这个

var i = 3400;
function progress() {
     i = i - 100;
     document.getElementById("progress").firstChild.data = i;
     window.setTimeout('progress();', 100);
}