Skip to content

Commit

Permalink
perf: The callback function for requestAnimationFrame has been extr…
Browse files Browse the repository at this point in the history
…acted into the main body of the `animate` method to avoid creating a new function on each animation loop
  • Loading branch information
damingerdai committed May 29, 2024
1 parent 60832d3 commit 8d81455
Showing 1 changed file with 30 additions and 20 deletions.
50 changes: 30 additions & 20 deletions packages/ngx-dom-confetti/src/lib/confetti-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,30 +101,40 @@ export class ConfettiRenderer {

private animate(root: HTMLElement, fettis: Array<IFetti>, dragFriction: number, decay: number, duration: number, stagger: number) {
let startTime: number;
let isActive = true;

const update = (time: number) => {
if (!isActive) return;

if (!startTime) startTime = time;
const elapsed = time - startTime;
const progress = startTime === time ? 0 : (time - startTime) / duration;
fettis.slice(0, Math.ceil(elapsed / stagger)).forEach(fetti => {
this.updateFetti(fetti, progress, dragFriction, decay);
});

if (time - startTime < duration) {
requestAnimationFrame(update);
} else {
fettis.forEach((fetti) => {
if (fetti.element.parentNode === root) {
root.removeChild(fetti.element);
}
})

isActive = false;
}
}

return new Promise<void>(resolve => {
const update = (time: number) => {
if (!startTime) startTime = time;
const elapsed = time - startTime;
const progress = startTime === time ? 0 : (time - startTime) / duration;
fettis.slice(0, Math.ceil(elapsed / stagger)).forEach(fetti => {
this.updateFetti(fetti, progress, dragFriction, decay);
});

if (time - startTime < duration) {
requestAnimationFrame(update);
} else {
fettis.forEach((fetti) => {
if (fetti.element.parentNode === root) {
root.removeChild(fetti.element);
}
})
requestAnimationFrame(update);

return new Promise<void>(resolve => {
const checkIfDone = setInterval(() => {
if (!isActive) {
clearInterval(checkIfDone);
resolve();
}
}

requestAnimationFrame(update);
}, 100);
});
}

Expand Down

0 comments on commit 8d81455

Please sign in to comment.