fix(home): counter counts exactly once, no restart on value refresh
AnimatedCounter restarted from 0 on every online-count cache refresh (~10s) because the effect depended on value. Rewrote it as a single requestAnimationFrame animation with ease-out; changes to value after the animation only update the display statically.
This commit is contained in:
1 parent
037b295b93
commit
c1cc1fdc1c
1 file changed
+22
-12
@@ -12,25 +12,35 @@ export function AnimatedCounter({
|
|||||||
}) {
|
}) {
|
||||||
const ref = useRef<HTMLSpanElement>(null);
|
const ref = useRef<HTMLSpanElement>(null);
|
||||||
const isInView = useInView(ref, { once: true, margin: "-50px" });
|
const isInView = useInView(ref, { once: true, margin: "-50px" });
|
||||||
|
const started = useRef(false);
|
||||||
const [display, setDisplay] = useState(0);
|
const [display, setDisplay] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isInView) return;
|
if (!isInView) return;
|
||||||
|
|
||||||
|
if (started.current) {
|
||||||
|
setDisplay(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
started.current = true;
|
||||||
|
|
||||||
const duration = 1200;
|
const duration = 1200;
|
||||||
const steps = 30;
|
const start = performance.now();
|
||||||
const increment = value / steps;
|
let raf = 0;
|
||||||
let current = 0;
|
|
||||||
let step = 0;
|
const tick = (now: number) => {
|
||||||
const id = setInterval(() => {
|
const progress = Math.min((now - start) / duration, 1);
|
||||||
step++;
|
const eased = 1 - (1 - progress) ** 3;
|
||||||
current = Math.min(Math.round(increment * step), value);
|
setDisplay(Math.round(eased * value));
|
||||||
setDisplay(current);
|
if (progress < 1) {
|
||||||
if (step >= steps) {
|
raf = requestAnimationFrame(tick);
|
||||||
clearInterval(id);
|
} else {
|
||||||
setDisplay(value);
|
setDisplay(value);
|
||||||
}
|
}
|
||||||
}, duration / steps);
|
};
|
||||||
return () => clearInterval(id);
|
|
||||||
|
raf = requestAnimationFrame(tick);
|
||||||
|
return () => cancelAnimationFrame(raf);
|
||||||
}, [isInView, value]);
|
}, [isInView, value]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in new issue
Block a user