Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useRafFn): option fpsLimit #3459

Merged
merged 3 commits into from Oct 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/core/useRafFn/index.ts
Expand Up @@ -23,6 +23,13 @@ export interface UseRafFnOptions extends ConfigurableWindow {
* @default true
*/
immediate?: boolean
/**
* The maximum frame per second to execute the function.
* Set to `undefined` to disable the limit.
*
* @default undefined
*/
fpsLimit?: number
}

/**
Expand All @@ -35,10 +42,12 @@ export interface UseRafFnOptions extends ConfigurableWindow {
export function useRafFn(fn: (args: UseRafFnCallbackArguments) => void, options: UseRafFnOptions = {}): Pausable {
const {
immediate = true,
fpsLimit = undefined,
window = defaultWindow,
} = options

const isActive = ref(false)
const intervalLimit = fpsLimit ? 1000 / fpsLimit : null
let previousFrameTimestamp = 0
let rafId: null | number = null

Expand All @@ -48,6 +57,11 @@ export function useRafFn(fn: (args: UseRafFnCallbackArguments) => void, options:

const delta = timestamp - (previousFrameTimestamp || timestamp)

if (intervalLimit && delta < intervalLimit) {
rafId = window.requestAnimationFrame(loop)
return
}

fn({ delta, timestamp })

previousFrameTimestamp = timestamp
Expand Down