简体   繁体   English

使用计时器 setInterval/clearInterval 将计时器重置为 0 用于秒表

[英]reset timer back to 0 by using the timer setInterval/clearInterval for stopwatch

Im working on code for a simple stopwatch.我正在编写一个简单秒表的代码。 Last obstacle for me is reset the time to zero.对我来说最后一个障碍是将时间重置为零。 The function resetTimer is where i am trying to implement the code. function resetTimer 是我尝试实现代码的地方。 So the webpage will display a page with a timer and three buttons;所以网页会显示一个带有计时器和三个按钮的页面; stop, start and reset.停止、启动和重置。 When a user clicks the reset button, the timer is supposed to reset back to zero.当用户单击重置按钮时,计时器应该重置为零。 I have been having trouble trying to make it work.我一直在尝试使它工作时遇到麻烦。 Any help/ideas would be clutch.任何帮助/想法都会很重要。 I hope i made myself clear.我希望我说清楚了。 Again i am trying to make the timer reset to 00:00:00我再次尝试将计时器重置为 00:00:00

window.onload = function () {
    //grab possible elements needed
    const timerEl = document.getElementById("timer-text")
    const startBtn = document.getElementById("start")
    const restartBtn = document.getElementById("restart");
    const stopBtn = document.getElementById('stop');

    //hold variables of time and set to 0
    let hours = parseInt('0');
    let minutes = parseInt('0');
    let seconds = parseInt('0');
    let time;

    function makeTwoNumbers(num) {
        if (num < 10) {
            return "0" + num
        }
        return num
    }
    
    //timer
    let timer = () => {
        seconds++
        //console.log(seconds)
        if (seconds == 60) {
            minutes++
            seconds = 0;
            hours = 0
        }
        if (minutes == 60) {
            hours++
            minutes = 0;
            hours = 0;
        }
        timerEl.textContent = makeTwoNumbers(hours)+ ": " + makeTwoNumbers(minutes) + ": " + makeTwoNumbers(seconds);
    }
    
    let runTheClock;
    
    //timer is running
    function runTimer() {
        runTheClock = setInterval(timer, 20);;
    }
    
    function stopTimer() {
        clearInterval(runTheClock)
    }
    
    //function will reset timer
    function resetTimer() {
        time--;
        timerEl.textContent;
        if (time === 0) {
            stopTimer();
            time = 0
        }
    }
    
    restartBtn.addEventListener("click", function () {
        resetTimer();
    })

    //button will pause the timer
    stopBtn.addEventListener("click", function () {
        stopTimer();
    })

    //button will start the timer
    startBtn.addEventListener("click", function () {
        runTimer();
    })


}

Here's a fixed and slightly refactored version.这是一个固定的和稍微重构的版本。

<html>
    <body>
        <div id="timer-text"></div>
        <button id="start">start</button>
        <button id="restart">restart</button>
        <button id="stop">stop</button>
    </body>
    <script>
    const timerEl = document.getElementById("timer-text")
    const startBtn = document.getElementById("start")
    const restartBtn = document.getElementById("restart");
    const stopBtn = document.getElementById('stop');

    let runTheClock;
    let seconds = 0;
    render(seconds);

    function makeTwoNumbers(num) {
        return ((num < 10) ? "0" : "") + num;
    }

    function tick() {
        seconds++;
        render(seconds);
    }
    
    function render(secs) {

        const hours = Math.floor(secs / 3600);
        const minutes = Math.floor(secs / 60) - (hours * 60);
        const seconds = secs % 60;

        const val = [hours, minutes, seconds].map(makeTwoNumbers).join(":");
        console.log(val);
        timerEl.textContent = val;
    }
    
    function runTimer() {
        runTheClock = setInterval(tick, 1000);
    }
    
    function stopTimer() {
        clearInterval(runTheClock)
    }
    
    function resetTimer() {
        seconds = 0;
        render(seconds);
    }
    
    restartBtn.addEventListener("click", resetTimer);
    stopBtn.addEventListener("click", stopTimer);
    startBtn.addEventListener("click", runTimer);

    </script>
</html>

In the reset function it just sets seconds back to 0 and sets the textContent value so it appears on the page.在重置 function 中,它只是将秒设置回 0 并设置textContent值,使其显示在页面上。 I separated out the calculating and drawing of the time into a render fucntion, so it can be reused whenever it needs to be re-rendered.我将时间的计算和绘制分离到一个render函数中,所以它可以在需要重新渲染时重复使用。

To explain the render function.解释渲染 function。

We only need to store the number of seconds as a persistent variable between the periodic function calls.我们只需要将秒数存储为周期性 function 调用之间的持久变量。 We can derive hours and minutes from it.我们可以从中得出小时和分钟。 This makes it much less error prone than trying to increment hours and minutes as well.这使得它比尝试增加小时和分钟更不容易出错。

To calculate hours we just divide seconds by 3600 (or 60 x 60 the number of seconds in an hour) and round down.要计算小时,我们只需将秒除以 3600(或 60 x 60 一小时的秒数)并向下取整。

To calculate minutes we can calculate the number of total minutes (seconds / 60 and round down) then subtract the number of minutes in the hours value we calculated (hours * 60).要计算分钟,我们可以计算总分钟数(秒 / 60 并向下取整),然后减去我们计算的小时值中的分钟数(小时 * 60)。

For seconds we use modulus or % which is just a fancy word for remainder.对于几秒钟,我们使用模数或% ,这只是余数的一个花哨的词。 So seconds % 60 gives us the remainder value of seconds / 60 .所以seconds % 60给了我们seconds / 60的余数。 For example 61 % 60 = 1. This isn't the only way these values could be calculated.例如 61 % 60 = 1。这不是计算这些值的唯一方法。

To build the display string.构建显示字符串。 I just put all of the hours, minutes and seconds in an array.我只是把所有的小时、分钟和秒放在一个数组中。 Then used the map method, which applies the function makeTwoNumbers to all of the values.然后使用map方法,该方法将 function makeTwoNumbers应用于所有值。 I then used the join method to join all the strings using the delimiter : .然后我使用join方法使用分隔符:连接所有字符串。 It just saves some typing and means you only reference makeTwoNumbers once, making it less work to use a different function later if you want to.它只是节省了一些输入,并且意味着您只引用makeTwoNumbers一次,如果您愿意,以后使用不同的 function 可以减少工作量。

Hope that helps.希望有帮助。

I realized that you could simply reset seconds, hours, and minutes to 0 and use a variable true.我意识到您可以简单地将秒、小时和分钟重置为 0 并使用变量 true。 This would reset it entirely to 0. I couldnt believe how simple it was这会将它完全重置为 0。我无法相信它是多么简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM