Javascript - 暂停具有 setTimeout 并显示分钟/秒的 IIFE 输出 - 番茄钟

标签 javascript jquery settimeout iife

我有两个显示分钟和秒的函数。在函数内部,我使用带有 setTimeout 的 IIFE 来计算时间。得到这个之后,很难弄清楚如果单击暂停按钮如何暂停显示。

计时器工作正常并且显示正确。

我意识到这可能不是一个好方法,但我花了很多时间(试图学习如何使用 IIFE),我不想放弃。如果必须的话,我会刮掉它。

更新 - 该计时器将从用户那里获取输入。可能需要 25 分钟。我希望它从那里开始倒计时,直到达到 0,并且用户可以随时暂停。

    let convertToSeconds = document.getElementById('timeValue').value * 60;
    let seconds = 60;

    function secondsCounter(time) {
        // let flag = document.getElementById('pauseButton').value;
        for (let i = seconds; i > 0; i--) {
            (function(x) {
                setTimeout(function() {
                    let remaining = seconds - x;
                    document.getElementById('displaySeconds').innerHTML = remaining;
                    console.log(remaining);
                }, i * 1000);
            })(i);
        }
    }

    function counter() {
        for (let i = convertToSeconds; i > 0; i--) {
            (function(minutes) {
                setTimeout(function() {
                    let remaining = Math.floor((convertToSeconds - minutes) / 60);
                    document.getElementById('displayMinutes').innerHTML = remaining;
                    console.log(remaining);
                }, i * 1000);

                setTimeout(function() {
                    secondsCounter(seconds);
                }, i * 60000);

            })(i);
        }

        secondsCounter(seconds);

    }

我尝试了一些方法。

  1. document.getElementById('displaySeconds').innerHTML = remaining; 周围使用标志和 if 语句因此,如果单击我的暂停按钮,标志会发生变化,并触发另一个 setTimeout (10 分钟)。 DOM 上的倒计时不会停止,它会继续进行。我只是想看看有什么 react ,但什么也没发生。像这样的东西:

    function secondsCounter(time) {
        let flag = document.getElementById('pauseButton').value;
    
        for (let i = seconds; i > 0; i--) {
            (function(x) {
                setTimeout(function() {
                    let remaining = seconds - x;
    
                    if (flag === 'yes') {
                        document.getElementById('displaySeconds').innerHTML = remaining;
                        console.log(remaining);
                    } else {
                        setTimeout(function() {
                            console.log(remaining);
                        }, 10000);
                    }
    
                }, i * 1000);
            })(i);
        }
    }
    
  2. 使用 setInterval 和clearInterval 没有执行任何操作。

这可能吗?不知道还能去哪里看。谢谢

最佳答案

如果不引用计时器、存储它然后调用 clearTimeout(timer),则无法停止/暂停 setTimeoutclearTimeout )clearInterval(timer)

所以,而不是:setTimeout(someFunciton)

您需要:timer = setTimeout(someFunciton)

并且,timer 变量需要在所有使用它的函数都可以访问的范围内声明。

参见setTimeout()了解详情。

如果没有引用计时器,您将无法停止它,这导致您徒劳地寻找其他方法来实现这一目标,这过度考虑了您实际需要的内容。

最后,我认为您应该只使用一个函数来完成所有倒计时,这样您就只需担心一个计时器。

最后,您可以使用 JavaScript Date 对象及其 get/set 小时、分钟和秒方法来执行相反的操作为你计数。

(function() {
      // Ask user for a time to start counting down from.
      var countdown = prompt("How much time do you want to put on the clock? (hh:mm:ss)");
  
      // Take that string and split it into the HH, MM and SS stored in an array   
      var countdownArray = countdown.split(":")      
  
      // Extract the individual pieces of the array and convert to numbers:
      var hh = parseInt(countdownArray[0],10);
      var mm = parseInt(countdownArray[1],10);
      var ss = parseInt(countdownArray[2],10); 
  
      // Make a new date and set it to the countdown value
      var countdownTime = new Date();
      countdownTime.setHours(hh, mm, ss);
  
      // DOM object variables
      var clock = null,  btnStart = null, btnStop = null;

      // Make a reference to the timer that will represent the running clock function
      var timer = null;

      window.addEventListener("DOMContentLoaded", function () {

        // Make a cache variable to the DOM element we'll want to use more than once:
        clock = document.getElementById("clock");
        btnStart = document.getElementById("btnStart");
        btnStop = document.getElementById("btnStop");

        // Wire up the buttons
        btnStart.addEventListener("click", startClock);
        btnStop.addEventListener("click", stopClock);

        // Start the clock
        startClock();

      });

      function startClock() {
        // Make sure to stop any previously running timers so that only
        // one will ever be running
        clearTimeout(timer);
        
        // Get the current time and display
        console.log(countdownTime.getSeconds());
        countdownTime.setSeconds(countdownTime.getSeconds() - 1);
        clock.innerHTML = countdownTime.toLocaleTimeString().replace(" AM", "");


        // Have this function call itself, recursively every 900ms
        timer = setTimeout(startClock, 900);
      }
      
      function stopClock() {
        // Have this function call itself, recursively every 900ms
        clearTimeout(timer);
      }

 }());
<div id="clock"></div>
<button id="btnStart">Start Clock</button>
<button id="btnStop">Stop Clock</button>

关于Javascript - 暂停具有 setTimeout 并显示分钟/秒的 IIFE 输出 - 番茄钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871623/

相关文章:

JavaScript 随机链接生成并在新选项卡中打开它们

javascript - Bx-slider 多个 slider 自定义控件

Javascript 使用按钮更改变量

javascript - jQuery 选择器获取同一列中的单元格

javascript - setTimeout 函数,以 Promise 解析值作为回调

javascript - 如何将 cls 放入 tagfield 编辑器中

javascript - js中如何使用科学计数法?

javascript - 在 React 中,我可以在另一个功能组件的主体内定义一个功能组件吗?

Javascript递归settimeout

javascript - 为什么使用 Promise.then 设置 CSS 属性实际上不会发生在 then block ?