Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/useRafLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export default function useRafLoop(

const step = useCallback((time: number) => {
if (rafActivity.current) {
rafCallback.current(time);
raf.current = requestAnimationFrame(step);
rafCallback.current(time);
}
}, []);

Expand Down
34 changes: 34 additions & 0 deletions tests/useRafLoop.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,40 @@ describe('useRafLoop', () => {
});

describe('returned methods', () => {
it('should keep one loop when restarting from the callback', () => {
const spy = jest.fn(() => {
if (spy.mock.calls.length === 1) {
hook.result.current[0]();
hook.result.current[1]();
}
});
const hook = renderHook(() => useRafLoop(spy));

requestAnimationFrame.step();
expect(spy).toBeCalledTimes(1);
requestAnimationFrame.step(3);
expect(spy).toBeCalledTimes(4);

hook.result.current[0]();
requestAnimationFrame.step();
expect(spy).toBeCalledTimes(4);
});

it('should cancel the pending frame when stopped from the callback', () => {
const spy = jest.fn(() => {
if (spy.mock.calls.length === 1) {
hook.result.current[0]();
}
});
const hook = renderHook(() => useRafLoop(spy));

requestAnimationFrame.step();
expect(hook.result.current[2]()).toBe(false);
hook.result.current[1]();
requestAnimationFrame.step(3);
expect(spy).toBeCalledTimes(4);
});

it('stop method should stop the loop', () => {
const spy = jest.fn();
const hook = renderHook(() => useRafLoop(spy), { initialProps: false });
Expand Down