如何使这个JavaScript定时器正常工作

How can I make this JavaScript Timer function properly?

本文关键字:工作 常工作 何使这 JavaScript 定时器      更新时间:2023-09-26

我正在尝试使用JavaScript制作计时器。问题是,当计时器达到0时,我无法停止计时器。我尝试过使用returnif语句,但似乎都不起作用。我走在正确的轨道上了吗?或者有更好的方法吗?

<input type="text" id="minutes" style="width:30px;text-align:center" maxlength="2" placeholder="00">
<span>:</span>
<input type="text" id="seconds" style="width:30px;text-align:center" maxlength="2" placeholder="00">
<button onclick="timer()">Set</button>
<script>
//This prototype correctly uses the modulus function when dealing with negative numbers.
Number.prototype.mod = function (m) {
    return ((this % m) + m) % m
}
function timer() {
    var minutes = document.getElementById('minutes').value //Value of minutes box.
    var seconds = document.getElementById('seconds').value //Value of seconds box.
    var initial = seconds * 1000 //Amount of seconds (converted to milliseconds) initially set.
    var milliseconds = (minutes * 60000) + (seconds * 1000) //Total amount of milliseconds set.
    setTimeout(function () {
        alert("Time's up!")
    }, milliseconds) //Display a message when the set time is up.
    /*'Decreases the minute by one after the initially set amount of seconds have passed.
    |*|Then, clears the interval and sets a new one to decrease the minute every 60 seconds.
    '*/
    test = setInterval(function () {
        minutes--;
        document.getElementById('minutes').value = minutes;
        clearInterval(test)
        setInterval(function () {
            minutes--;
            document.getElementById('minutes').value = minutes
        }, 60000)
    }, initial)
    //Seconds are set to decrease by one every 1000 milliseconds, then be displayed in the seconds box.
    setInterval(function () {
        seconds--;
        document.getElementById('seconds').value = seconds.mod(60)
    }, 1000)
}

当您只需要四个不同的计时器函数(setTimer和两个setIntervals)时,您就有了它们。JSFiddle

function timer() {
    var minutes = document.getElementById('minutes').value //Value of minutes box.
    var seconds = document.getElementById('seconds').value //Value of seconds box.
    var intervalTimer = setInterval(function () {
        seconds--;
        if (seconds < 0) {
            seconds = 59;
            minutes--;
        }
        document.getElementById('minutes').value = minutes;
        document.getElementById('seconds').value = seconds;
        if (minutes == 0 && seconds == 0) {
            alert("Time's up!");
            clearInterval(intervalTimer);
        }
    }, 1000);
}

通常,您需要确保每个setInterval都有一个名称(var x = setInterval...),并在以后清除(clearInterval(x))。如果出于某种原因你真的想这样做,你可以有单独的计时器(一个用于指定秒数后开始的分钟,然后每60秒重复一次,一个用于秒,还有一个用于显示消息),只要你在倒计时为零时清除所有间隔计时器。

然而,使用两个定时器可能是有意义的。这将确保"时间到"消息在应该出现的时候真正出现,即使间隔计时器中有任何不精确的地方。

function timer() {
    var minutes = document.getElementById('minutes').value,
        seconds = document.getElementById('seconds').value,
        intervalTimer = setInterval(function () {
        seconds--;
        if (seconds < 0) {
            seconds = 59;
            minutes--;
        }
        document.getElementById('minutes').value = minutes;
        document.getElementById('seconds').value = seconds;
    }, 1000);
    setTimer(function () {
        alert("Time's up!");
        clearInterval(intervalTimer);
    }, minutes * 60000 + seconds * 1000);
}

我改进了Stuart的答案:fiddle

基本上是一样的,只是它工作正常:

function clearTimer() {
    clearInterval(intervalTimer);
}
var intervalTimer;
function timer() {
    var minutes = document.getElementById('minutes').value //Value of minutes box.
    var seconds = document.getElementById('seconds').value //Value of seconds box.
    intervalTimer = setInterval(function () {
        seconds--;
        if (seconds < 0) {
            seconds += 60;
            minutes--;
        }
        if (minutes < 0) {
            alert("Time's up!");
            clearTimer();
        } else {
            document.getElementById('minutes').value = minutes;
            document.getElementById('seconds').value = seconds;
        }
    }, 1000);
}

我不是一个优秀的javascript程序员,但也许这会有所帮助。我用打字稿做的http://www.typescriptlang.org/Playground/

但我会做不同的计时,并使用javascript日期对象来计算差异。这是一个简单的例子,说明我将如何开始创建一个时间(没有日期对象)

javascript

var Timer = (function () {
    function Timer(time) {
        this.accuracy = 1000;
        this.time = time;
    }
    Timer.prototype.run = function (button) {
        var _this = this;
        this.time -= 1; //this is inaccurate, for accurate time use the date objects and calculate the difference.
        //http://www.w3schools.com/js/js_obj_date.asp
        button.textContent = this.time.toString();
        if (this.time > 0) {
            setTimeout(function () {
                return _this.run(button);
            }, 1000);
        }
    };
    return Timer;
})();
var time = new Timer(10);
var button = document.createElement('button');
time.run(button);
document.body.appendChild(button);

打字稿(如果你想知道的话)

class Timer {
    accuracy = 1000;//update every second
    time: number;
    constructor(time: number) {
        this.time = time;
    }
    run(button: HTMLButtonElement) {
        this.time -=1;//this is inaccurate, for accurate time use the date objects and calculate the difference.
        //http://www.w3schools.com/js/js_obj_date.asp
        button.textContent = this.time.toString();
        if(this.time > 0)
        {
            setTimeout(()=> this.run(button),1000);
        }
    }
}
var time = new Timer(10)
var button = document.createElement('button');
time.run(button);
document.body.appendChild(button);