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): add delta and timestamp #2493

Merged
merged 2 commits into from Dec 16, 2022
Merged
Changes from 1 commit
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
26 changes: 21 additions & 5 deletions packages/core/useRafFn/index.ts
@@ -1,9 +1,21 @@
import { ref } from 'vue-demi'
import type { Fn, Pausable } from '@vueuse/shared'
import type { Pausable } from '@vueuse/shared'
import { tryOnScopeDispose } from '@vueuse/shared'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'

interface RafFnCallbackArguments {
innocenzi marked this conversation as resolved.
Show resolved Hide resolved
/**
* Time elapsed between this and the last frame.
*/
delta: number

/**
* Time elapsed since the creation of the web page. See {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin Time origin}.
*/
timestamp: DOMHighResTimeStamp
}

export interface UseRafFnOptions extends ConfigurableWindow {
/**
* Start the requestAnimationFrame loop immediately on creation
Expand All @@ -20,27 +32,31 @@ export interface UseRafFnOptions extends ConfigurableWindow {
* @param fn
* @param options
*/
export function useRafFn(fn: Fn, options: UseRafFnOptions = {}): Pausable {
export function useRafFn(fn: (args: RafFnCallbackArguments) => void, options: UseRafFnOptions = {}): Pausable {
const {
immediate = true,
window = defaultWindow,
} = options

const isActive = ref(false)
let previousFrameTimestamp = 0
let rafId: null | number = null

function loop() {
function loop(timestamp: DOMHighResTimeStamp) {
if (!isActive.value || !window)
return

fn()
const delta = timestamp - previousFrameTimestamp
fn({ delta, timestamp })

previousFrameTimestamp = timestamp
rafId = window.requestAnimationFrame(loop)
}

function resume() {
if (!isActive.value && window) {
isActive.value = true
loop()
rafId = window.requestAnimationFrame(loop)
}
}

Expand Down