calculate-clock-offset.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. // Limit the iterations, just in case we're running in an environment where Date.now() has been mocked and is
  15. // constant.
  16. for (let i = 0; i < 1e6 && cur === start; i++) {
  17. cur = Date.now();
  18. }
  19. // At this point |cur| "just" became equal to the next millisecond -- the unseen digits after |cur| are approximately
  20. // all 0, and |cur| is the closest to the actual value of the UNIX time. Now, get the current global monotonic clock
  21. // value and do the remaining calculations.
  22. return cur - getGlobalMonotonicClockMS();
  23. }
  24. if (clockIsAccurate) {
  25. // Warm up the function.
  26. calculateClockOffset();
  27. calculateClockOffset();
  28. calculateClockOffset();
  29. module.exports = calculateClockOffset;
  30. } else {
  31. module.exports = undefined;
  32. }