日期
文档指出:
JavaScript 日期基于自 UTC 时间 1970 年 1 月 1 日午夜起的毫秒级时间值
单击开始按钮,然后单击结束按钮。它将显示2次单击之间的秒数。
毫秒差异位于变量中。使用它来查找秒/分钟/小时/或您需要的内容timeDiff
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>
或者为现代浏览器做的另一种方式
使用 performance.now()
返回一个值,该值表示自时间原点以来经过的时间。此值是小数中微秒的双精度值。
时间原点是一个标准时间,它被认为是当前文档生存期的开始。
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>