sync-time.mjs 885 B

12345678910111213141516171819202122232425262728293031
  1. import { MotionGlobalConfig } from 'motion-utils';
  2. import { frameData } from './frame.mjs';
  3. let now;
  4. function clearTime() {
  5. now = undefined;
  6. }
  7. /**
  8. * An eventloop-synchronous alternative to performance.now().
  9. *
  10. * Ensures that time measurements remain consistent within a synchronous context.
  11. * Usually calling performance.now() twice within the same synchronous context
  12. * will return different values which isn't useful for animations when we're usually
  13. * trying to sync animations to the same frame.
  14. */
  15. const time = {
  16. now: () => {
  17. if (now === undefined) {
  18. time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming
  19. ? frameData.timestamp
  20. : performance.now());
  21. }
  22. return now;
  23. },
  24. set: (newTime) => {
  25. now = newTime;
  26. queueMicrotask(clearTime);
  27. },
  28. };
  29. export { time };