我一直在尝试制作此计时器网页,该网页显示在输入初始秒时显示秒数减少。我首先运行一个创建H2元素的函数,然后打印出输入的初始值。然后,我使用setInterval执行一个函数,该函数将H2元素的值降低1,直到达到零为止。达到0后,我会使用Clear Interval结束它。由于某种原因,执行时间太长,并且网页崩溃而无需在屏幕上输出任何内容。我不明白执行时间太长了,请帮助我。有其他方法可以做到吗?这是代码 -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TIMER</title>
</head>
<body>
<label>Enter the number of seconds for the timer <input id='initial' type="text">
</label> <br>
Press the button to start the timer <br>
<button id="start_timer">Timer</button> <br><br>
<script type="text/javascript">
var timerValue=document.getElementById('initial');
var buttonEl=document.getElementById("start_timer");
function reduceTime(){
countDown.textContent=parseFloat(countDown.textContent)-1;
}
function initial(){
countDown=document.createElement('h2')
countDown.textContent=timerValue.value;
while(parseFloat(countDown.textContent)>0){
timer=window.setInterval(reduceTime,1000);
}
if(parseFloat(countDown.textContent)===0){
window.clearInterval(timer);
}
}
buttonEl.addEventListener('click',initial);
</script>
</body>
</html>
将您的新h2
元素附加到DOM,在reduceTime()
中移动clearInterval
的测试,然后删除setInterval
的while
循环:
var timerValue = document.getElementById('initial');
var buttonEl = document.getElementById("start_timer");
function reduceTime() {
if (parseFloat(countDown.textContent) === 0) {
window.clearInterval(timer);
} else {
countDown.textContent = parseFloat(countDown.textContent) - 1;
}
}
function initial() {
countDown = document.createElement('h2');
document.body.appendChild(countDown)
countDown.textContent = timerValue.value;
timer = window.setInterval(reduceTime, 1000);
}
buttonEl.addEventListener('click', initial);
<label>Enter the number of seconds for the timer <input id='initial' type="text">
</label> <br> Press the button to start the timer <br>
<button id="start_timer">Timer</button>
问题是,当您在while
周期中添加新间隔时,当条件在1秒内保持不变时。您也没有使用可变的countDown
做任何事情。这是一个修复程序:
var timerValue=document.getElementById('initial');
var buttonEl=document.getElementById("start_timer");
var countDown = document.getElementById("countDown");
var timer;
function reduceTime(){
var time = parseFloat(countDown.textContent)-1;
if (time < 0) {
clearInterval (timer);
return;
}
countDown.textContent=time;
}
function initial(){
countDown.textContent=timerValue.value;
timer = window.setInterval(reduceTime,1000);
}
buttonEl.addEventListener('click',initial);
<label>
Enter the number of seconds for the timer <input id='initial' type="text">
</label>
<br />
Press the button to start the timer <br>
<button id="start_timer">Timer</button> <br><br>
<p>
<h2 id="countDown"></h2>
</p>