Skip to content

Commit

Permalink
Merge pull request #1065 from davidjerleke/bug/#1064
Browse files Browse the repository at this point in the history
[Bug]: RangeError Maximum call stack size exceeded
  • Loading branch information
davidjerleke authored Nov 20, 2024
2 parents 53fddf7 + 169a7bd commit 98eb5c4
Showing 1 changed file with 12 additions and 29 deletions.
41 changes: 12 additions & 29 deletions packages/embla-carousel/src/components/Animations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,26 @@ import { EventStore } from './EventStore'
import { WindowType } from './utils'

export type AnimationsUpdateType = (engine: EngineType) => void
export type AnimationsRenderType = (
engine: EngineType,
lagOffset: number
) => void
export type AnimationsRenderType = (engine: EngineType, alpha: number) => void

export type AnimationsType = {
init: () => void
destroy: () => void
start: () => void
stop: () => void
update: () => void
render: (lagOffset: number) => void
render: (alpha: number) => void
}

export function Animations(
ownerDocument: Document,
ownerWindow: WindowType,
update: () => void,
render: (lagOffset: number) => void
render: (alpha: number) => void
): AnimationsType {
const documentVisibleHandler = EventStore()
const fixedTimeStep = 1000 / 60

let lastTimeStamp: number | null = null
let accumulatedTime = 0
let animationId = 0
Expand All @@ -40,36 +38,21 @@ export function Animations(
documentVisibleHandler.clear()
}

function shouldUpdate(): boolean {
return accumulatedTime >= fixedTimeStep
}

function updateAndRemoveAccumulatedTime(): void {
update()
accumulatedTime -= fixedTimeStep
if (shouldUpdate()) updateAndRemoveAccumulatedTime()
}

function renderWithAlpha(): void {
const alpha = accumulatedTime / fixedTimeStep
render(alpha)
}

function animate(timeStamp: DOMHighResTimeStamp): void {
if (!animationId) return

if (!lastTimeStamp) {
lastTimeStamp = timeStamp
update()
renderWithAlpha()
}
if (!lastTimeStamp) lastTimeStamp = timeStamp

const timeElapsed = timeStamp - lastTimeStamp
lastTimeStamp = timeStamp
accumulatedTime += timeElapsed

if (shouldUpdate()) updateAndRemoveAccumulatedTime()
renderWithAlpha()
while (accumulatedTime >= fixedTimeStep) {
update()
accumulatedTime -= fixedTimeStep
}

const alpha = accumulatedTime / fixedTimeStep
render(alpha)

if (animationId) {
animationId = ownerWindow.requestAnimationFrame(animate)
Expand Down

0 comments on commit 98eb5c4

Please sign in to comment.