From f39f8f916357ec9e665e4606c228c071d2e914e4 Mon Sep 17 00:00:00 2001 From: verekia <522007+verekia@users.noreply.github.com> Date: Sun, 6 Oct 2024 08:29:27 +0700 Subject: [PATCH] fix: take throttling into account in mainLoop callback delta --- packages/core/src/main-loop.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/core/src/main-loop.ts b/packages/core/src/main-loop.ts index cd11795..1ac8fc2 100644 --- a/packages/core/src/main-loop.ts +++ b/packages/core/src/main-loop.ts @@ -1,4 +1,5 @@ export type MainLoopEffectCallback = (callback: { + time: number delta: number elapsed: number callbackCount: number @@ -13,7 +14,7 @@ type StageNumber = number const callbacks = new Map>() const callbackLastExecutions = new WeakMap() -const state = { delta: 0, elapsed: 0, callbackCount: 0 } +const state = { time: 0, delta: 0, elapsed: 0, callbackCount: 0 } let previousTime = performance.now() let running = false let animationFrameId: number | null = null @@ -21,15 +22,14 @@ let animationFrameId: number | null = null const mainLoop = (time: number) => { if (!running) return - state.delta = (time - previousTime) / 1000 - state.elapsed += state.delta - let callbackCount = 0 for (const callbacksSet of callbacks.values()) { callbackCount += callbacksSet.size } state.callbackCount = callbackCount + state.time = time + Array.from(callbacks.keys()) .sort((a, b) => a - b) .forEach(stage => { @@ -50,13 +50,20 @@ export const addMainLoopEffect = ( callback: MainLoopEffectCallback, options?: MainLoopEffectOptions, ) => { - const throttledCallback = (state: { delta: number; elapsed: number; callbackCount: number }) => { + const throttledCallback = (state: { + time: number + delta: number + elapsed: number + callbackCount: number + }) => { const now = performance.now() const lastExecution = callbackLastExecutions.get(callback) || 0 const throttleInterval = options?.throttle || 0 if (now - lastExecution >= throttleInterval) { callbackLastExecutions.set(callback, now) + state.delta = (state.time - previousTime) / 1000 + state.elapsed += state.delta callback(state) } }