设置以按钮开头的30分钟计时器

时间:2019-03-22 01:35:02

标签: javascript html

我正在使用一个计时器,该计时器会在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>

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

2 个答案:

答案 0 :(得分:0)

您需要对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>

答案 1 :(得分:0)

尝试:

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>