我一直在尝试制作这个计时器网页,当输入初始秒数时显示秒数减少。我首先运行一个创建 h2 元素的函数,然后打印出输入的初始值。然后我使用 setInterval 执行一个函数,将 h2 元素的值减 1 直到它达到零。一旦它达到 0,我就使用 clearInterval 来结束它。由于某种原因,执行时间太长,网页崩溃而没有在屏幕上输出任何内容。我不明白执行时间太长的地方,请帮帮我。还有其他方法可以做到吗?这是代码-
<!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,将 clearInterval
的测试移至 reduceTime()
并删除 while
循环 setInterval
:
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>
关于javascript - 如何使用 javascript 创建一个计时器,以便它创建一个 div 元素来显示 javascript 执行的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47966040/