Skip to content

Commit de98f6a

Browse files
author
Leroy Korterink
committed
Add delta time to test implementation in storybook
1 parent 926e091 commit de98f6a

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

src/hooks/useAnimationLoop/useAnimationLoop.stories.tsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,16 @@ export default {
99
};
1010

1111
function DemoComponent(): ReactElement {
12-
const [currentTimestamp, setCurrentTimestamp] = useState(Date.now);
12+
const [delta, setDelta] = useState(0);
13+
const [currentTimestamp, setCurrentTimestamp] = useState(0);
14+
1315
const [isRunning, toggleIsRunning] = useToggle(true);
16+
1417
useAnimationLoop(() => {
15-
setCurrentTimestamp(Date.now);
18+
const timestamp = Date.now();
19+
20+
setDelta(timestamp - currentTimestamp);
21+
setCurrentTimestamp(timestamp);
1622
}, isRunning);
1723

1824
return (
@@ -24,7 +30,8 @@ function DemoComponent(): ReactElement {
2430
<div className="card border-dark" data-ref="test-area">
2531
<div className="card-header">Test Area</div>
2632
<div className="card-body">
27-
<p>{currentTimestamp}</p>
33+
<p>Current time: {currentTimestamp}</p>
34+
<p>Delta: {delta}</p>
2835

2936
<button
3037
type="button"

src/hooks/useAnimationLoop/useAnimationLoop.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,17 @@ export function useAnimationLoop(callback: (delta: number) => void, enabled = fa
1313
const lastTimeRef = useRef(0);
1414
const callbackRef = useRefValue(callback);
1515

16-
const tick = useCallback((time: number): void => {
17-
const delta = time - lastTimeRef.current;
18-
lastTimeRef.current = time;
16+
const tick = useCallback(
17+
(time: number): void => {
18+
const delta = time - lastTimeRef.current;
19+
lastTimeRef.current = time;
1920

20-
callbackRef.current?.(delta);
21+
callbackRef.current?.(delta);
2122

22-
animationFrameRef.current = requestAnimationFrame(tick);
23-
}, []);
23+
animationFrameRef.current = requestAnimationFrame(tick);
24+
},
25+
[callbackRef],
26+
);
2427

2528
const play = useCallback(() => {
2629
lastTimeRef.current = performance.now();

0 commit comments

Comments
 (0)