如何衡量在Javascript上经过的时间? [英] How to measure time elapsed on Javascript?
问题描述
我创建了一个简单的游戏,当用户单击完16个框时,该计时器将启动和结束计时器.
I created a simple game that start and ends the timer when the user finishes clicking on 16 boxes.
我想测量用户完成游戏所花费的时间. 如何使用Javascript完成此操作?
I want to measure the elapsed time for the user to complete the game. How do I do it using Javascript?
我查看了不同的答案像这样,但是我很难过了解他人的代码.
I took a look at different answers like this, but I had hard time understanding others' code.
我认为它看起来像这样.
I would assume it to look like this.
Timer Start: When user clicks the first box
Timer End: When user clicks the last box
推荐答案
Date
文档指出:
The Date
documentation states that :
JavaScript日期基于毫秒的时间值 自1970年1月1日午夜以来,UTC
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
单击开始按钮,然后单击结束按钮.它将显示两次单击之间的秒数.
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
毫秒diff在变量timeDiff
中.播放以查找秒/分钟/小时/或您需要的内容
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;
function start() {
startTime = new Date();
};
function end() {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff);
console.log(seconds + " seconds");
}
<button onclick="start()">Start</button>
<button onclick="end()">End</button>
或者为现代浏览器实现的另一种方式
OR another way of doing it for modern browser
使用 performance.now()
会返回一个值表示从时间原点开始经过的时间.此值为小数秒的倍数.
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
时间原点是标准时间,被认为是当前文档生命周期的开始.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff);
console.log(seconds + " seconds");
}
<button onclick="start()">Start</button>
<button onclick="end()">End</button>
这篇关于如何衡量在Javascript上经过的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!