倒计时使用香草JavaScript

Countdown using vanilla JavaScript

本文关键字:JavaScript 香草 倒计时      更新时间:2023-09-26

我有一个textarea和3 buttons的网页。textarea接收号码。第一个button启动从数字到0的倒计时,具有延迟输出(每秒一个数字,因此如果N为10,则需要10秒)。第二个button暂停倒计时,第三个button继续倒计时(没有重新开始)。在执行期间的任何时候,按第一个button将重新启动倒计时,无论textarea中的数字是多少。这是我到目前为止的代码:

<!DOCTYPE html>
<html>
    <body>
        <h2>Insert a number:</h2>
        <textarea id="input"></textarea>
        <br/>
        <button id="start" onclick="begin()">BEGIN</button>
        <button id="pause" onclick="pause()">PAUSE</button>
        <button id="resume" onclick="resume()">RESUME</button>
        <h1 id="result"></h1>
        <script>
            var isCounting=true,
                input=document.getElementById("input"),
                countSec;
            function begin() {
                countSec=input.value;
                if (isNaN(countSec)) alert("NaN");
                count();
            }
            function pause() {
                isCounting=false;
            }
            function resume() {
                isCounting=true;
                count();
            }
            function count() {
                var i,
                    bck=countSec;
                for (i=0; i<=bck; i++) {
                    document.getElementById("result").innerHTML=countSec;
                    countSec--;
                }
            }
        </script>
    </body>
</html>

是否有一种方法可以在countSec--之后停止执行1秒?我已经尝试了2个小时做一些事情与日期对象和setTimeout,但我只是不知道如何在每次for迭代后暂停

这是一个选项:

    <script>
        var input=document.getElementById("input"),
            countSec,
            timer = null;
        function begin() {
            countSec=input.value;
            if (isNaN(countSec)) alert("NaN");
            if( timer === null ) {
                timer = setTimeout( count, 1000 );
            }
        }
        function pause() {
            clearTimeout( timer );
            timer = null;
        }
        function resume() {
            if( timer === null ) {
                timer = setTimeout( count, 1000 );
            }
        }
        function count() {
            if( countSec > 0 ) {
                countSec--;
            }
            document.getElementById("result").innerHTML = countSec;
            if( countSec > 0 ) {
                timer = setTimeout( count, 1000 );
            }
        }
    </script>

begin被调用时,它在count上设置一个计时器,间隔1秒。

当稍后调用count时,它减少计数器,更新html并计划自己在1秒后使用setTimeout()被召回(当然,除非计数器达到零)

计划任务存储在timer中,因此可以使用clearTimeout()取消它(参见pause())

要恢复倒计时,只需再次调用count()

timer在计数器未运行时设置为null,并且在启动前检查,以确保只有一个计数器在运行。

如果每次countSec减法之间需要延迟,那么我建议您使用setInterval函数。我把你的代码修改如下:

var isCounting=true,
    input=document.getElementById("input"),
    countSec
    interval;
function begin() {
    countSec=input.value;
    if (isNaN(countSec)) alert("NaN");
    count();
}
function pause() {
    isCounting=false;
    clearInterval(interval);
}
function resume() {
    isCounting=true;
    count();
}
function count() {
    var i,
        bck=countSec;
    document.getElementById("result").innerHTML=bck;               
    interval = setInterval(function() {
        countSec--;
        document.getElementById("result").innerHTML=countSec;               
    }, 1000);
}

具体来说,我创建了一个全局interval变量,它将保持对间隔的引用。我在count()中设置间隔,然后在间隔的每个刻度处更新#result ID(其延迟为1000ms)。为了暂停,我清除了间隔。事实上,我留下了很多你的代码,即使其中一些没有被使用(如isCounting);

下面是实际代码:https://jsfiddle.net/exex7jh0/

这听起来像是实现Javascript内置异步间隔操作的完美场景。

计时器应该以setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)为中心。基本上,您将设置间隔为每秒触发,这将增加您的计数器。

要暂停倒计时,您需要使用clearInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval)。您还可以使用intervalID来确定setInterval定时器是否正在运行。

这些积木应该能让你走下去。

我认为大多数解决方案已经回答了你的问题。在您的解决方案中包含间隔操作是一个更好的主意,因为这更合适,JS已经提供了它。

  • 也是一个更好的主意,分开你的JS和HTML。(避免内联事件处理程序)

<h2>Insert a number:</h2>
<textarea id="input"></textarea>
<br/>
<button id="start">BEGIN</button>
<button id="pause">PAUSE</button>
<button id="resume">RESUME</button>
<h1 id="result"></h1>

JS

// Bind the click events
document.getElementById('start').addEventListener('click', begin);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('resume').addEventListener('click', resume);
var input = document.getElementById("input");
var countSec;
var timer;
function begin() {
  debugger;
  countSec = input.value;
  if (isNaN(countSec)) alert("NaN");
  count();
  enableTimer();
}
function pause() {
  clearInterval(timer);
}
function resume() {
  enableTimer();
}
function count() {
  if (countSec >= 0) {
    document.getElementById("result").innerHTML = countSec;
  } else {
    clearInterval(timer);
  }
  countSec--;
}
// enable the timer again 
function enableTimer() {
   timer = setInterval(function() {
      count();
    }, 1000);
}

JsFiddle

您想要的是您的count函数包含一个自调用定时器,如下所示:

var timer;
function count() {
    var result = document.getElementById("result");
    step();
    function step() {
        result.innerHTML=countSec;
        countSec--;
        if (countSec > 0) {
            timer = setTimeout(step, 1000);
        }
    }
}

但是要知道,超时并不是真正的1000ms。如果你想要准确,你就必须将其与一切开始的时间进行比较。并降低间隔:

var timer,
    start,
    moment,
    input = document.getElementById("input"),
    result = document.getElementById("result");
function begin() {
    var from = ((parseInt(input.value) + 1) * 1000);
    start = Date.now() + from;
    setTimeout(count, 40);
}
function pause() {
    clearTimeout(timer);
}
function resume() {
    start = Date.now() + (moment * 1000);
    count();
}
function count() {
    moment = parseInt((start - Date.now()) / 1000);
    result.innerHTML = moment;
    if (moment > 0) {
        timer = setTimeout(count, 200);
    }
}

当计数为0时,您可以使用setInterval, intervalID和clearInterval

var isCounting = true,
    input = document.getElementById("input"),
    countSec,
    intervalID;
function begin() {
    countSec = +input.value;
    if (isNaN(countSec)) {
        alert("NaN");
        return;
    }
    document.getElementById("result").innerHTML = countSec;
    intervalID = setInterval(count, 1000);
}
function pause() {
    isCounting = false;
}
function resume() {
    isCounting = true;
}
function count() {
    if (countSec === 0) {
        clearInterval(intervalID);
        return;
    }
    if (isCounting) {
        countSec--;
        document.getElementById("result").innerHTML = countSec;
    }
}
<h2>Insert a number:</h2>
<textarea id="input"></textarea><br/>
<button id="start" onclick="begin()">BEGIN</button>
<button id="pause" onclick="pause()">PAUSE</button>
<button id="resume" onclick="resume()">RESUME</button>
<h1 id="result"></h1>

这里有另一个解决方案

<!DOCTYPE html>
<html>
  <body>
    <h2>Insert a number:</h2>
    <textarea id="input"></textarea>
    <br/>
    <button id="start" onclick="begin()">BEGIN</button>
    <button id="pause" onclick="pause()">PAUSE</button>
    <button id="resume" onclick="resume()">RESUME</button>
    <h1 id="result"></h1>
    <script>
      let isCounting = true;
      let input = document.getElementById("input");
      let countSec = 0;
      let countDownInterval = false;
      function begin() {
        countSec = input.value;
        if (isNaN(countSec)) alert("NaN");
        count();
      }
      function pause() {
        isCounting = false;
      }
      function resume() {
        isCounting = true;
      }
      function count() {
        // Let's check we're doing a restart 
        if (countDownInterval) {
          clearInterval(countDownInterval);
        }
        countDownInterval = setInterval(function() {
          if (isCounting) {
            document.getElementById("result").innerHTML = countSec;
            countSec -= 1;
            // Times up ??
            if (countSec == -1) {
              clearInterval(countDownInterval);
              countDownInterval = null;
            }
          }
        }, 1000);
      }
    </script>
  </body>
</html>

jsfiddle