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:
@@ -9,4 +9,5 @@ export * from './useScrollParent';
|
||||
export * from './useEventListener';
|
||||
export * from './usePageVisibility';
|
||||
export * from './useCustomFieldValue';
|
||||
export * from './useRaf';
|
||||
export * from './onMountedOrActivated';
|
||||
|
||||
@@ -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 () => {};
|
||||
}
|
||||
Reference in New Issue
Block a user