Checkout the article on how I built this composable here.

Description

The useRAF composable leverages the requestAnimationFrame API to ensure optimal performance and synchronization with the browser's rendering loop. Pass it a callback function and duration, and your callback will be called on every requestAnimationFrame until your duration is hit. It also provides the ability to start, pause, and reset the execution of your callback. It runs immediately upon invocation, unless you specify a third parameter of false, enabling you to start running your callbacks manually by calling the start function.

import { ref } from 'vue'
import { useRaf } from '@/composables/useRaf'

const { pause, start, reset } = useRaf(
  ({ progress, timeElapsed }) => {
    ...
  },
  3000,
  false
)

Arguments

KeyTypeDefaultDescription
callbackfunctionrequiredRAF callback function. Receives an object with progress, timeElapsed, and timeStamp properties.
durationnumberrequiredThe duration of the loop in ms.
immediatebooleanfalseBegin the loop immediately on invocation.

Returns

KeyTypeDescription
startfunctionManually start the execution of your callback.
pausefunctionPause the execution of your callback.
resetfunctionReset the execution state of your callback.