CKTIS / JavaScript
Event.timeStamp and Event.type: creation time and event name
`event.type` tells you what kind of event it is; `event.timeStamp` tells you when it was created, in milliseconds relative to a time origin.
Version: Current web platform; runtime support varies
Syntax
event.type
event.timeStampEvent.timeStamp/type is shorthand for two read-only properties on a DOM event object: event.timeStamp and event.type. They are not methods or static properties of the Event constructor. They belong to the web platform API, not ECMAScript 2024, so availability depends on the runtime.
event.type is the event's case-sensitive name as a string. new Event("click") sets the type to "click", which matches a listener registered with addEventListener("click", ...) but not addEventListener("Click", ...). The name alone does not prove a user clicked.
event.timeStamp is a DOMHighResTimeStamp: a JavaScript number in milliseconds from the relevant global object's time origin to event creation. It does not record when the listener runs. Browsers may reduce timing precision to mitigate timing attacks and fingerprinting, so two events can have the same timestamp.
Subtract timestamps directly only if they share a time origin. Do not subtract event.timeStamp directly from Date.now(), which counts milliseconds since the Unix epoch. Put timestamps from different contexts, such as a window and a worker, on a common time origin before comparing them.
Examples
{
const target = new EventTarget();
const event = new Event("lesson-ready");
const createdAt = event.timeStamp;
target.addEventListener("lesson-ready", (received) => {
console.log(`type: ${received.type}`);
console.log(`timeStamp is a finite number: ${Number.isFinite(received.timeStamp)}`);
console.log(`timeStamp unchanged: ${received.timeStamp === createdAt}`);
});
target.dispatchEvent(event);
}Result
type: lesson-ready timeStamp is a finite number: true timeStamp unchanged: true
Run this in a browser console. `dispatchEvent()` calls the matching listener synchronously. The example checks that the timestamp is a finite number and equals the value read before dispatch. It does not print the timestamp itself because that value varies by run.
Related lessons
- JavaScript · Lesson 35 · Intermediate · Version: 3