Microsecond

Master high-precision timing in JavaScript with the Performance API for accurate performance measurement and optimization.

Introduction

The web platform provides powerful timing APIs that enable developers to measure code execution with sub-millisecond precision. Understanding these high-resolution timing mechanisms is essential for performance optimization, animation development, and building responsive user interfaces. Microsecond-level timing allows developers to identify performance bottlenecks that would be invisible with standard millisecond-resolution timing, enabling finer-grained optimization of critical rendering paths and JavaScript execution.

Why High-Precision Timing Matters

High-precision timing serves multiple purposes in modern web development. Performance profiling requires accurate measurements to identify slow code paths, while animation development demands precise timing to achieve smooth, consistent frame rates. The Performance API provides timestamps that are monotonic--meaning they always increase and are unaffected by system clock adjustments--making them ideal for measuring elapsed time between operations.

For developers building performance-critical applications, mastering these timing APIs is a foundational skill that enables data-driven optimization decisions and measurable improvements in user experience.

MDN's high precision timing documentation

The DOMHighResTimeStamp Type

The DOMHighResTimeStamp type represents high-resolution time values in the web platform. Unlike traditional timestamps, DOMHighResTimeStamp provides fractional millisecond values, enabling measurements in microseconds (millionths of a second). This precision is crucial for performance-critical applications where even small timing variations impact user experience.

Unit and Precision

DOMHighResTimeStamp expresses time in milliseconds, but with floating-point precision that can represent values down to the microsecond level. For example, a value of 15.234567 milliseconds represents 15 milliseconds and 234.567 microseconds. This level of detail allows developers to distinguish between operations that complete in rapid succession, which would appear identical with standard integer millisecond timestamps.

Security-Driven Precision Reduction

Modern browsers implement security measures that reduce timing precision to prevent timing-based fingerprinting attacks. In standard contexts, precision is typically limited to 100 microseconds (0.1 milliseconds), while cross-origin isolated contexts can access full microsecond precision. This trade-off balances developer needs for accurate profiling with user protection against malicious timing-based attacks.

MDN's high precision timing documentation

The performance.now() Method

The performance.now() method returns a DOMHighResTimeStamp representing the time elapsed since the time origin of the current browsing context. This method is the primary interface for accessing high-resolution timestamps in web applications and is available in both main threads and Web Workers.

Basic Usage

Calling performance.now() returns the current high-resolution timestamp as a floating-point number. Developers capture a timestamp before an operation, execute the operation, then capture another timestamp and calculate the difference to determine elapsed time.

const startTime = performance.now();

// Execute the operation to measure
processData(largeDataset);

const endTime = performance.now();
const elapsed = endTime - startTime;

console.log(`Operation completed in ${elapsed.toFixed(3)} milliseconds`);

performance.now() vs Date.now()

Unlike Date.now(), which returns milliseconds since the Unix epoch and can be affected by system clock adjustments, performance.now() provides monotonically increasing values that are immune to clock skew. Date.now() values can decrease or jump forward when system time synchronization occurs, making them unreliable for measuring elapsed time.

For measuring scroll performance with high precision, see our guide on scrollx for viewport scroll position timing.

W3C Performance Timing Primer

Understanding Time Origins

The time origin defines the baseline from which performance.now() values are measured. Different browsing contexts have different time origins, which affects how timestamps from different contexts can be compared or synchronized.

Time Origin by Context Type

In Window contexts, the time origin represents the time when navigation to the current document began. For Web Workers and Service Workers, the time origin is the time when the worker execution started. This distinction is important when measuring time across multiple execution contexts, such as when coordinating timing between a main thread and worker threads.

Using timeOrigin

The Performance.timeOrigin property provides the absolute time value corresponding to the time origin, enabling conversion between relative and absolute timestamps when needed for cross-context comparisons.

// Get relative timestamp
const relativeTime = performance.now();

// Convert to absolute timestamp
const absoluteTime = performance.timeOrigin + relativeTime;

For coordinate-based timing and positioning, explore the xywh API which complements timing measurements for viewport-related operations.

Security and Cross-Origin Isolation

Browser security mechanisms limit timing precision to protect users from timing-based attacks. Understanding these limitations and how to work with or around them is important for developers who need high-precision timing for legitimate purposes.

Precision Limitations by Context

Standard browsing contexts receive timing values with approximately 100 microsecond precision, which is sufficient for most profiling needs while providing meaningful protection against fingerprinting. Cross-origin isolated contexts can access full microsecond precision for demanding performance measurement scenarios.

Enabling Cross-Origin Isolation

To achieve full precision, websites must serve themselves with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

Chrome's cross-origin isolation guide

Practical Applications

High-precision timing enables various performance-critical development scenarios that require accurate measurements of code execution, rendering performance, and user interaction responsiveness.

Code Profiling and Benchmarking

Performance profiling requires accurate timing to identify slow code paths and measure the impact of optimizations. By capturing performance.now() timestamps before and after specific operations, developers can quantify execution time, compare different implementation approaches, and verify optimization results.

Animation Timing

Smooth animations require consistent frame rates, typically targeting 60 frames per second (approximately 16.67 milliseconds per frame). Microsecond precision enables developers to measure frame rendering times accurately and adjust animation complexity to maintain smooth visual presentation.

Measuring Rendering Performance

Understanding how long different rendering phases take helps optimize the critical rendering path. High-precision timing can measure style calculation, layout operations, paint operations, and compositing durations.

const start = performance.now();
// Measure rendering-intensive operation
element.innerHTML = generateContent();
const end = performance.now();
console.log(`Rendering took ${end - start}ms`);

For advanced scroll-related timing, including scroll lines and smooth scrolling, see our guide on scrollbylines. For teams building modern web applications, these timing techniques are essential for maintaining responsive user experiences and meeting performance benchmarks.

Best Practices

When working with high-precision timing, following established practices ensures accurate measurements and avoids common pitfalls that can skew timing results.

Multiple Measurements

Single timing measurements can be affected by system variability. Taking multiple measurements and calculating statistical summaries (such as median or average) provides more reliable performance data.

Accounting for Warm-up Effects

JavaScript engines apply optimizations during execution that can make later runs faster than initial runs. Timing code after allowing the engine to optimize measures steady-state performance rather than including compilation overhead.

Avoiding Measurement Overhead

The act of measuring can itself affect performance. Minimizing measurement overhead by reducing the number of timing calls ensures that measurements reflect actual code performance.

For scroll-related timing controls and behavior, explore the css-overscroll-behavior guide. When integrating these timing techniques into your optimization workflow, consistent measurement practices yield the most actionable insights for improving application responsiveness.

Related Concepts

Understanding microsecond timing within the broader context of web performance APIs enables comprehensive performance measurement and optimization strategies.

Performance Timeline API

The Performance Timeline provides a unified interface for accessing various performance measurements, including resource timing, navigation timing, and user-defined marks and measures. This API complements the scroll-timeline-axis for scroll-linked animations.

User Timing API

The User Timing API extends the Performance interface with mark() and measure() methods, enabling developers to define named timestamps and measure durations between them.

Resource Timing API

Resource timing provides detailed timing information for individual resources loaded by the page, including DNS lookup time, connection setup time, and request/response durations using DOMHighResTimeStamp.

Explore related timing concepts in our guides on JavaScript performance optimization and web performance fundamentals.

Key Takeaways

Essential points for implementing high-precision timing

DOMHighResTimeStamp

Floating-point timestamp type providing sub-millisecond precision for accurate performance measurements.

Monotonic Clock

performance.now() uses a monotonic clock immune to system clock adjustments, ensuring reliable duration calculations.

Security Trade-offs

Browser security limits precision to 100μs in standard contexts, requiring cross-origin isolation for full precision.

Multiple Contexts

Different contexts (Window, Worker) have different time origins, requiring careful consideration when comparing timestamps.

Frequently Asked Questions