值
此值是從時間起點到事件建立時經過的毫秒數。如果全域性物件是 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① |
瀏覽器相容性
載入中…