我有一个计时器,它的计数从o到100,并显示在 ptag 中,其ID为 countdowntimer
我试图从运行计时器中单击按钮时显示当前时间。
我还想重置计时器按钮后点击。
我如何实现它?
var timeleft = 1;
var downloadTimer = setInterval(function(){
timeleft++;
document.getElementById("countdowntimer").textContent = timeleft;
if(timeleft >= 100)
clearInterval(downloadTimer);
},1000);
function timenow()
{
var timenow=document.getElementById("timetaken").textContent = timeleft;
}
<p> Time <span id="countdowntimer">0 </span></p>
<p> Time Taken <span id="timetaken">0 </span></p>
<button onclick="timenow">Click to viw time taken</button>
答案 0 :(得分:1)
首先,您应该在onclick事件中触发该函数,其次,您应该在该函数中重置timelefet值。
您的代码应如下所示
<!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">
<title>Document</title>
</head>
<body>
<p> Time <span id="countdowntimer">0 </span></p>
<p> Time Taken <span id="timetaken">0 </span></p>
<button onclick="timenow()">Click to viw time taken</button> <!-- changed timenow to timenow() -->
<script>
var sum = 0;
var timeleft = 1;
var downloadTimer = setInterval(function () {
timeleft++;
document.getElementById("countdowntimer").textContent = timeleft;
if (timeleft >= 100)
clearInterval(downloadTimer);
}, 1000);
function timenow() {
sum += timeleft;
var timenow = document.getElementById("timetaken").textContent = sum;
timeleft = 0;
document.getElementById("countdowntimer").textContent = timeleft;
}
</script>
</body>
</html>
答案 1 :(得分:1)
您的onclick函数事件未正确绑定。要重置计时器,只需将按钮点击功能中的timeleft
var重置为0
var timeleft = 1;
var downloadTimer = setInterval(function(){
timeleft++;
document.getElementById("countdowntimer").textContent = timeleft;
if(timeleft >= 100)
clearInterval(downloadTimer);
},1000);
function timenow()
{
document.getElementById("timetaken").textContent = timeleft;
timeleft=0;
document.getElementById("countdowntimer").textContent = timeleft;
}
<p> Time <span id="countdowntimer">0 </span></p>
<p> Time Taken <span id="timetaken">0 </span></p>
<button onclick="timenow()">Click to viw time taken</button>