Reputation: 205
I have a timer which counts from o to 100 and display it in ptag with id countdowntimer
Im trying to display the current time when i click a button from the timer running.
also i want to reset the timer after button click.
how do i achieve it?
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>
Upvotes: 2
Views: 142
Reputation: 19
First of all you should fire the function in onclick event, secondly you should reset timelefet value in that function.
Your code should look something like this
<!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>
Upvotes: 1
Reputation: 885
Your onclick function event is not bind correctly. To reset timer just reset timeleft
var in button click function to 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>
Upvotes: 1