Skip to content

Commit

Permalink
fix: keep track of animationFrameId when pausing and resuming main loop
Browse files Browse the repository at this point in the history
  • Loading branch information
verekia committed Aug 28, 2024
1 parent 2929d77 commit c5c4f92
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/core/src/main-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const callbackLastExecutions = new WeakMap<MainLoopEffectCallback, number>()
const state = { delta: 0, elapsed: 0 }
let previousTime = performance.now()
let running = false
let animationFrameId: number | null = null

const mainLoop = (time: number) => {
if (!running) return
Expand All @@ -30,7 +31,7 @@ const mainLoop = (time: number) => {
})

previousTime = time
requestAnimationFrame(mainLoop)
animationFrameId = requestAnimationFrame(mainLoop)
}

export const addMainLoopEffect = (
Expand All @@ -57,7 +58,7 @@ export const addMainLoopEffect = (
if (!running) {
running = true
previousTime = performance.now() // Reset time to avoid large delta after pause
requestAnimationFrame(mainLoop)
animationFrameId = requestAnimationFrame(mainLoop)
}

return () => {
Expand All @@ -68,12 +69,18 @@ export const addMainLoopEffect = (
}
}

export const pauseMainLoop = () => (running = false)
export const pauseMainLoop = () => {
running = false
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId)
animationFrameId = null
}
}

export const resumeMainLoop = () => {
if (!running && callbacks.size > 0) {
running = true
previousTime = performance.now() // Reset time to avoid large delta after pause
requestAnimationFrame(mainLoop)
animationFrameId = requestAnimationFrame(mainLoop)
}
}

0 comments on commit c5c4f92

Please sign in to comment.