Skip to content

Commit

Permalink
Add delta time to test implementation in storybook
Browse files Browse the repository at this point in the history
  • Loading branch information
leroykorterink committed May 15, 2023
1 parent 926e091 commit de98f6a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
13 changes: 10 additions & 3 deletions src/hooks/useAnimationLoop/useAnimationLoop.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,16 @@ export default {
};

function DemoComponent(): ReactElement {
const [currentTimestamp, setCurrentTimestamp] = useState(Date.now);
const [delta, setDelta] = useState(0);
const [currentTimestamp, setCurrentTimestamp] = useState(0);

const [isRunning, toggleIsRunning] = useToggle(true);

useAnimationLoop(() => {
setCurrentTimestamp(Date.now);
const timestamp = Date.now();

setDelta(timestamp - currentTimestamp);
setCurrentTimestamp(timestamp);
}, isRunning);

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

<button
type="button"
Expand Down
15 changes: 9 additions & 6 deletions src/hooks/useAnimationLoop/useAnimationLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ export function useAnimationLoop(callback: (delta: number) => void, enabled = fa
const lastTimeRef = useRef(0);
const callbackRef = useRefValue(callback);

const tick = useCallback((time: number): void => {
const delta = time - lastTimeRef.current;
lastTimeRef.current = time;
const tick = useCallback(
(time: number): void => {
const delta = time - lastTimeRef.current;
lastTimeRef.current = time;

callbackRef.current?.(delta);
callbackRef.current?.(delta);

animationFrameRef.current = requestAnimationFrame(tick);
}, []);
animationFrameRef.current = requestAnimationFrame(tick);
},
[callbackRef],
);

const play = useCallback(() => {
lastTimeRef.current = performance.now();
Expand Down

0 comments on commit de98f6a

Please sign in to comment.