值
此值是从时间起点到事件创建时经过的毫秒数。如果全局对象是 Window,则时间起点是用户单击链接的时刻,或启动文档加载的脚本的时刻。在 worker 中,时间起点是 worker 创建的时刻。
该值是 DOMHighResTimeStamp,精确到 5 微秒 (0.005 毫秒),但为了防止 指纹识别,精度会降低。
示例
HTML
html
<p>
Focus this iframe and press any key to get the current timestamp for the
keypress event.
</p>
<p>timeStamp: <span id="time">-</span></p>
JavaScript
js
function getTime(event) {
const time = document.getElementById("time");
time.firstChild.nodeValue = event.timeStamp;
}
document.body.addEventListener("keypress", getTime);
结果
时间精度降低
为了防止计时攻击和 指纹识别,event.timeStamp 的精度可能会根据浏览器设置进行舍入。在 Firefox 中,privacy.reduceTimerPrecision 首选项默认启用,默认为 2 毫秒。您还可以启用 privacy.resistFingerprinting,在这种情况下,精度将为 100 毫秒或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds 的值,以较大的为准。
例如,在降低时间精度的情况下,event.timeStamp 的结果将始终是 2 的倍数,或者在启用 privacy.resistFingerprinting 的情况下是 100(或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds)的倍数。
js
// reduced time precision (2ms) in Firefox 60
event.timeStamp;
// Might be:
// 9934
// 10362
// 11670
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
event.timeStamp;
// Might be:
// 53500
// 58900
// 64400
// …
规范
| 规范 |
|---|
| DOM # ref-for-dom-event-timestamp① |
浏览器兼容性
加载中…