Course contentsShow
← Web Development
Lesson 756 of 2,98213. DOM EventsFree lesson

event.timeStamp and event.isTrusted

Using timestamp for timing analysis and isTrusted to distinguish user-initiated from programmatic events.

event.timeStamp and event.isTrusted

You'll learn how to use event.timeStamp to measure timing and event.isTrusted to verify whether events came from real user actions or were triggered by code.

What Are These Properties?

Every event object carries two useful properties for analysis and security:

event.timeStamp records when the event was created, measured in milliseconds since the page loaded (or since a fixed time origin). Think of it like a timestamp on a receipt—it tells you when something happened.

event.isTrusted is a boolean flag that tells you whether the event was generated by a genuine user action (true) or by your JavaScript code (false). It's like a seal of authenticity distinguishing real clicks from simulated ones.

Why They Matter

Timing Analysis: Use timeStamp to measure how quickly users respond, calculate delays between events, or detect double-clicks vs single clicks by comparing timestamps.

Security & Validation: Use isTrusted to ensure critical actions (like form submissions or payment confirmations) came from actual users, not automated scripts or malicious code trying to trigger events programmatically.

Common Patterns

document.addEventListener('click', (event) => {
  console.log(`Event occurred at: ${event.timeStamp}ms`);
  console.log(`User-initiated: ${event.isTrusted}`);
});

// Measure double-click timing
let lastClick = 0;
document.addEventListener('click', (event) => {
  const timeBetween = event.timeStamp - lastClick;
  if (timeBetween < 300) {
    console.log('Fast double-click detected!');
  }
  lastClick = event.timeStamp;
});

Events dispatched with code will have isTrusted: false, while genuine user interactions always return true.

Key Takeaway: Use event.timeStamp for timing measurements and interaction analysis, and event.isTrusted to verify events originated from real user actions rather than programmatic triggers.