事件:timeStamp 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

注意:此功能在 Web Workers 中可用。

Event 介面的只讀屬性 timeStamp 返回事件建立時的時間(以毫秒為單位)。

此值是從時間起點到事件建立時經過的毫秒數。如果全域性物件是 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①

瀏覽器相容性