steven-tey / precedent

An opinionated collection of components, hooks, and utilities for your Next.js project.
https://precedent.dev
MIT License
4.69k stars 409 forks source link

counting-numbers.tsx displays negative count when switching tabs #28

Closed tautastic closed 1 year ago

tautastic commented 1 year ago

The issue:

Screenshot 2023-03-07 at 22-29-17 Precedent - Building blocks for your Next js project

Steps to reproduce:

Open the precedent website and quickly switch to another tab while the counter is still counting up. Wait for a few seconds and then go back to the precedent tab.

I'm not familiar with the codebase but I'll try to figure out how this happens.

tautastic commented 1 year ago

The problem occurs when const progress = timePassed / duration; is bigger than 1. This can happen when switching tabs because the timestamps passed to animateCount by requestAnimationFrame kept growing while the client was on another tab.

The problem can be fixed inside the easeOutQuad function by ensuring that t/d is always less or equal to d.

const easeOutQuad = (t: number, b: number, c: number, d: number) => {
  t = t > d ? d : t / d;
  return Math.round(-c * t * (t - 2) + b);
};
steven-tey commented 1 year ago

You, sir, are a freaking legend! Thank you for the PR – it works like a charm!