JavaScript Stopwatch

A JavaScript stopwatch needs two separate ideas: a timer to refresh the display and a reliable elapsed-time calculation. For elapsed duration, calculate from timestamps such as performance.now() instead of assuming every interval callback arrives exactly on time.

0.00 s
const start = performance.now();
// ...later
const elapsed = performance.now() - start;

How a JavaScript Stopwatch Works Top ↑

The refresh timer does not define the elapsed time; it only decides how often the screen is updated. The elapsed value should be calculated from the recorded start timestamp plus any previously accumulated duration.

Why Use performance.now() for Elapsed Time? Top ↑

performance.now() provides a high-resolution monotonic timestamp designed for measuring elapsed durations. Unlike wall-clock time, it is not intended to jump when the system clock is adjusted.

Start the Stopwatch Without Creating Duplicate Intervals Top ↑

if (timerId !== null) return;
startedAt = performance.now();
timerId = setInterval(render, 50);

Stop and Resume Without Losing Elapsed Time Top ↑

elapsed += performance.now() - startedAt;
clearInterval(timerId);
timerId = null;

On the next Start, keep the accumulated elapsed value and record a new startedAt.

Reset the Stopwatch Top ↑

clearInterval(timerId);
timerId = null;
elapsed = 0;

Choose a Display Refresh Interval Top ↑

A 10 ms refresh does not make a stopwatch more accurate; it only updates the DOM more often. A moderate refresh such as 50–100 ms is enough for many educational stopwatch displays. For animation tied to screen painting, requestAnimationFrame() may be a better display loop.

Can Date.now() Be Used? Top ↑

Date.now() works when you need a wall-clock timestamp or when persistence across reloads matters. For measuring duration within the current page session, performance.now() is generally a better fit.

Common Stopwatch Mistakes Top ↑

  • Incrementing a counter by 10/100/1000 and assuming every interval was exact.
  • Starting multiple intervals on repeated Start clicks.
  • Resetting the display but leaving the timer running.
  • Using an extremely short interval that causes unnecessary DOM work.

Other window examples retained from the original learning path: add to favorites and redirect.

The original related analog-clock example remains available: HTML canvas clock demo. Also see countdown timer and real-time clock.




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer