vant/packages/vant/docs/markdown/use-raf.en-US.md
2023-08-27 15:57:10 +08:00

1.4 KiB

useRaf

Intro

Provide convenient call and cancellation of requestAnimationFrame.

Usage

Single Call

By using the useRaf method, you can execute a function before the next browser repaint.

import { useRaf } from '@vant/use';

export default {
  setup() {
    let count = 0;
    useRaf(() => {
      console.log(++count); // It will only be executed once.
    });
  },
};

Loop Calls

By using the isLoop option, you can execution of a function repeatedly at a specified interval until it is canceled.

import { useRaf } from '@vant/use';

export default {
  setup() {
    let count = 0;
    const cancelRaf = useRaf(
      () => {
        console.log(++count); // Execute infinitely until canceled

        if (count === 5) {
          cancelRaf();
        }
      },
      {
        isLoop: true, // Enable the loop
        interval: 100, // Set call interval
      },
    );
  },
};

API

Type Declarations

function useRaf(
  callback: () => void,
  options: {
    interval?: number;
    isLoop?: boolean;
  },
): void;

Params

Name Description Type Default
callback Callback () => void -
options Options { interval?: number; isLoop?: boolean } { interval: 0; isLoop: false }