倒计时使用香草JavaScript
Countdown using vanilla JavaScript
我有一个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);
这听起来像是实现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。(避免内联事件处理程序)