shadcn-ahooks

useRafInterval

A hook implements with requestAnimationFrame for better performance. The API is consistent with useInterval, the advantage is that the execution of the timer can be stopped when the page is not rendering, such as page hiding or minimization.

Overview

A hook implements with requestAnimationFrame for better performance. The API is consistent with useInterval, the advantage is that the execution of the timer can be stopped when the page is not rendering, such as page hiding or minimization.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRafInterval.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRafInterval.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRafInterval.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRafInterval.json

A hook implements with requestAnimationFrame for better performance. The API is consistent with useInterval, the advantage is that the execution of the timer can be stopped when the page is not rendering, such as page hiding or minimization.

Please note that the following two cases are likely to be inapplicable, and useInterval is preferred:

  • the time interval is less than 16ms
  • want to execute the timer when page is not rendering;

requestAnimationFrame will automatically downgrade to setInterval in node environment

Examples

Default usage

Advanced usage

API

useRafInterval(
  fn: () => void,
  delay?: number | undefined,
  options?: Options
): fn: () => void;

Params

PropertyDescriptionType
fnThe function to be executed every delay milliseconds.() => void
delayThe time in milliseconds, the timer should delay in between executions of the specified function. The timer will be cancelled if delay is set to undefined.number | undefined
optionsConfig of the interval behavior.Options

Options

PropertyDescriptionTypeDefault
immediateWhether the function should be executed immediately on first executionbooleanfalse

Result

PropertyDescriptionType
clearIntervalclear interval() => void

On this page