Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(useRafFn): add delta and timestamp (#2493)
* feat: add `delta` and `timestamp` to `useRafFn`

* refactor: rename raf function callback arguments interface
  • Loading branch information
innocenzi committed Dec 16, 2022
1 parent fdd4dbf commit 692d024
Showing 1 changed file with 21 additions and 5 deletions.
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'

export interface UseRafFnCallbackArguments {
/**
* 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: UseRafFnCallbackArguments) => 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

0 comments on commit 692d024

Please sign in to comment.