首页 > 解决方案 > Display current time from timer

问题描述

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>

标签: javascripthtmlcss

解决方案


您的 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>


推荐阅读