我正在尝试编写一个简单的Tabata计时器。到目前为止,它仍然有效,但是当我尝试根据存储在变量中的值尝试多次重复计数时,问题就来了。因此,假设我们从10开始到0,并且想要重复两次此计数。会说:当我按下按钮时,在计数开始之前,程序将检查具有次数的变量是否为NaN或其中是否包含数字。如果是NaN(因为我不想重复),它将开始从10倒数到0,然后停止。好的,这部分有效。但是,如果我说我想重复倒数两次呢?我在变量“ var times”中输入了要重复的次数,比方说2,然后使用如下的for循环:
for(var i=0; i<times; i++){}
但是,当我开始倒数计时时,与其重复两次,而是跳过许多数字作为时间变量值。这是为什么?
提前致谢
这是我的代码。
var times = 2;
var counter = 0;
var operation;
document.getElementById("timer").textContent = 10;
function calculate(){
counter = document.getElementById("timer").textContent
operation = setInterval(function(){
if(counter >= 1 && counter <= 10){
counter -- ;
document.getElementById("timer").textContent = counter;
}
else if(counter == 0){
clearInterval(operation);
document.getElementById("timer").textContent = 10;
}
},1000);
}
document.getElementById("btn").addEventListener("click", function(){
for(var i=0; i<times; i++){
calculate();
}
})
.btn{
position: absolute;
width: 100%;
top: 20%;
margin:auto;
text-align: center;
}
.timer{
position: absolute;
width: 100%;
top:30%;
margin:auto;
text-align: center;
font-size: 10rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="btn">
<button id="btn">
<h1>Click me</h1>
</button>
</div>
<div class="timer">
<p id="timer"></p>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
我弄清楚了,问题在于,当您执行for循环时,它会调用两次setinterval,因此对于这种情况,您必须使用递归,这是此情况下的工作代码->
var times = 2;
var counter = 0;
var operation;
document.getElementById("timer").textContent = 10;
function calculate(){
counter = document.getElementById("timer").textContent
operation = setInterval(function(){
if(counter >= 1 && counter <= 10){
counter -- ;
document.getElementById("timer").textContent = counter;
}
else if(counter == 0){
times--
console.log(times)
if(times > 0){
document.getElementById("timer").textContent = 10;
clearInterval(operation);
calculate()
}else if(times == 0){
clearInterval(operation);
document.getElementById("timer").textContent = 10;
}
}
},1000);
}
.btn{
z-index: 9999;
position: absolute;
width: 100%;
top: 20%;
margin:auto;
text-align: center;
}
.timer{
position: absolute;
width: 100%;
top:30%;
margin:auto;
text-align: center;
font-size: 10rem;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="btn">
<button onClick="calculate()" id="btn">
<h1>Click me</h1>
</button>
</div>
<div class="timer">
<p id="timer"></p>
</div>
</div>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句