Date Now Versus Performance Now
Date.now is wall-clock whole milliseconds while performance.now is monotonic with sub-millisecond precision, so durations need the latter.
Code
// Date.now() versus performance.now(): wall clock versus monotonic clock.
// Date.now can jump with NTP syncs and only resolves to whole milliseconds,
// so elapsed time must be measured with performance.now()
function busyFor(ms) {
const deadline = performance.now() + ms;
let checksum = 0;
while (performance.now() < deadline) checksum = (checksum + 1) % 1e9;
return checksum;
}
const perfStart = performance.now();
busyFor(10);
const perfElapsed = performance.now() - perfStart;
console.log('performance.now elapsed:', perfElapsed.toFixed(3), 'ms');
const dateStart = Date.now();
busyFor(10);
const dateElapsed = Date.now() - dateStart;
console.log('Date.now elapsed:', dateElapsed, 'ms (whole ms only)');
console.log('Date.now is always an integer:', Number.isInteger(Date.now()));
console.log('performance.now never goes backwards:', performance.now() >= perfStart);
console.log('timeOrigin is epoch ms:', performance.timeOrigin > 1e12);
console.log('Date.now is epoch ms:', Date.now() > 1e12);Output
Captured from a sandboxed run of this snippet in the build pipeline.
performance.now elapsed: 14.785 ms
Date.now elapsed: 10 ms (whole ms only)
Date.now is always an integer: true
performance.now never goes backwards: true
timeOrigin is epoch ms: true
Date.now is epoch ms: trueHow it works
The short read: the function busyFor, doing all the work.
One loop does the cycling here: while (performance.now() < deadline) checksum = (checksum + 1) % 1e9;.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Putting it to use
Signature: function busyFor(ms)
The file’s steps show up in the output as performance.now elapsed:, Date.now elapsed:, Date.now is always an integer:.
Core lines
while (performance.now() < deadline) checksum = (checksum + 1) % 1e9;
const perfElapsed = performance.now() - perfStart;
const dateElapsed = Date.now() - dateStart;
Interactive Tools for This Topic
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `busyFor` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.