calculate-clock-offset.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. // This files implements the calculation of the offset between the global monotonic clock and UNIX time. This value is
  3. // known as |t1| in the calculation of "time origin timestamp" in the spec. This value needs to be calculated once and
  4. // can be used in all subsequent Performance instances.
  5. //
  6. // However, if the clock is not fast enough, the export is undefined to signify that we should use Date.now() to get the
  7. // time origin timestamp with millisecond accuracy, per spec.
  8. const { getGlobalMonotonicClockMS } = require("./global-monotonic-clock");
  9. const clockIsAccurate = require("./clock-is-accurate");
  10. // This function assumes the clock is accurate.
  11. function calculateClockOffset() {
  12. const start = Date.now();
  13. let cur = start;
  14. while (cur === start) {
  15. cur = Date.now();
  16. }
  17. // At this point |cur| "just" became equal to the next millisecond -- the unseen digits after |cur| are approximately
  18. // all 0, and |cur| is the closest to the actual value of the UNIX time. Now, get the current global monotonic clock
  19. // value and do the remaining calculations.
  20. return cur - getGlobalMonotonicClockMS();
  21. }
  22. if (clockIsAccurate) {
  23. // Warm up the function.
  24. calculateClockOffset();
  25. calculateClockOffset();
  26. calculateClockOffset();
  27. module.exports = calculateClockOffset;
  28. } else {
  29. module.exports = undefined;
  30. }