设置一个从按钮开始的30分钟计时器



我正在处理30分钟后的计时器。我想从按钮开始。这就是我到目前为止的。

<!DOCTYPE html>
    <html>
    <body>
    <p>30 minute count down.</p>
    <button onclick="countDown()">Start</button>
    <div id="status"></div>
    <script>
    function countDown() {
	    var secs = 1800;
  	    var mins = secs / 60;
	    var element = document.getElementById(status);
	    element.innerHTML = "You have "+mins.toFixed(2)+" minutes";
	    if(secs < 1) {
		    element.innerHTML = '<h2>You have no time left!</h2>';
	    }
	    secs--;
	    setTimeout('countDown()',1000);
    }
    </body>
    </html>

它不起作用。请帮助新手!谢谢

您需要对getElementById使用引号 - 例如"status"。还会更改功能的工作方式:

var secs = 1800;
function countDown() {
  var mins = secs / 60;
  var element = document.getElementById("status");
  element.innerHTML = "You have " + mins.toFixed(2) + " minutes";
  secs--;
  setTimeout(countDown, 1000);
  if (secs < 1) {
    element.innerHTML = '<h2>You have no time left!</h2>';
    secs = 1800;
  }
}
<p>30 minute count down.</p>
<button onclick="countDown()">Start</button>
<div id="status"></div>

尝试以下:

function countDown() {
    var secs = 1800;
    var mins;
    var element = document.getElementById('status');
    
    setInterval(function(){
      mins = secs / 60;
      element.innerHTML = "You have "+mins.toFixed(2)+" minutes";
      if(secs < 1) {
          element.innerHTML = '<h2>You have no time left!</h2>';
      }  
      secs--;
    }, 1000)  
}
<p>30 minute count down.</p>
<button onclick="countDown()">Start</button>
<div id="status"></div>

最新更新