feat(vant-use): add new useRaf method (#12211)

* feat(utils): add useRaf

* docs: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update

* chore: update
This commit is contained in:
Simon He
2023-08-27 15:19:25 +08:00
committed by GitHub
parent ad194d4c57
commit f967e6c5cf
7 changed files with 198 additions and 0 deletions
+1
View File
@@ -9,4 +9,5 @@ export * from './useScrollParent';
export * from './useEventListener';
export * from './usePageVisibility';
export * from './useCustomFieldValue';
export * from './useRaf';
export * from './onMountedOrActivated';
+41
View File
@@ -0,0 +1,41 @@
import { inBrowser } from '..';
interface UseRafOptions {
interval?: number;
isLoop?: boolean;
}
export function useRaf(
fn: FrameRequestCallback,
options?: UseRafOptions,
): () => void {
if (inBrowser) {
const { interval = 0, isLoop = false } = options || {};
let start: number;
let isStopped = false;
let rafId: number;
const stop = () => {
isStopped = true;
cancelAnimationFrame(rafId);
};
const frameWrapper = (timestamp: number) => {
if (isStopped) return;
if (start === undefined) {
start = timestamp;
} else if (timestamp - start > interval) {
fn(timestamp);
start = timestamp;
if (!isLoop) {
stop();
return;
}
}
rafId = requestAnimationFrame(frameWrapper);
};
rafId = requestAnimationFrame(frameWrapper);
return stop;
}
return () => {};
}