如何在 HTML5 和 Javascript 中添加计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34278816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:29:13  来源:igfitidea点击:

How to add a timer in HTML5 and Javascript?

javascriptcsshtml

提问by Frank

I'm trying to to add a timer for a Snake Game and to start it simultaneously when the game starts and to stop it when it's finished. Any help please? Many thanks!

我正在尝试为贪吃蛇游戏添加一个计时器,并在游戏开始时同时启动它并在游戏结束时停止它。请问有什么帮助吗?非常感谢!

回答by Manuel

The example below (just sample code) it will count 5 secs and then alert the total seconds. You need to make the math to get hours, minutes, seconds.

下面的示例(只是示例代码)将计算 5 秒,然后提醒总秒数。您需要进行数学运算才能获得小时、分钟、秒。

$(document).ready(function(){
var secs = 0;
var id = setInterval(function(){ 
    secs++; console.log(secs);
  if(secs> 5){
    clearInterval(id);
    alert('Total Time: ' + secs + ' seconds');
   }
}, 1000);
});

Then you can put the logic inside a start/stop method or wherever you need to place it.

然后您可以将逻辑放在启动/停止方法中或您需要放置它的任何地方。

With pure Javascript:

使用纯 Javascript:

window.onload = function() {
var secs = 0;
    var id = setInterval(function(){ 
        secs++; console.log(secs);
      if(secs> 5){
        clearInterval(id);
        alert('Total Time: ' + secs + ' seconds');
       }
    }, 1000);
};

回答by mat3e

Take a look here:

看看这里:

function changeValue() {
  document.getElementById("demo").innerHTML = ++value;
}

var timerInterval = null;
function start() {
  stop(); // stoping the previous counting (if any)
  value = 0;
  timerInterval = setInterval(changeValue, 1000);  
}
var stop = function() {
  clearInterval(timerInterval);
}
<p>A script on this page starts this clock:</p>

<p id="demo">0</p>

<button onclick="start()">Start time</button>
<button onclick="stop()">Stop time</button>