useRaf
Throttles callbacks to the next animation frame with cancel-then-request deduplication. Cleans up automatically on scope disposal.
Usage
The useRaf composable wraps requestAnimationFrame with a cancel-then-request pattern that deduplicates rapid calls. It returns a callable function that requests an animation frame, automatically canceling any pending frame.
<script setup lang="ts">
import { useRaf } from '@vuetify/v0'
import { ref } from 'vue'
const position = ref(0)
const updatePosition = useRaf((timestamp) => {
position.value = Math.sin(timestamp / 1000) * 100
})
// Call to request frame (cancels pending)
updatePosition()
// Manual cancel if needed
updatePosition.cancel()
// Check if frame is pending
console.log(updatePosition.isActive.value)
</script>Architecture
useRaf provides a lightweight wrapper around requestAnimationFrame:
Examples
Key Features
Cancel-Then-Request Pattern
Each call cancels any pending frame before requesting a new one. This deduplicates rapid calls, ensuring only the latest request executes:
const update = useRaf(() => {
// This callback only runs once per frame
})
// These rapid calls result in only ONE frame callback
update()
update()
update()Automatic Cleanup
The composable automatically cancels pending frames when the Vue scope is disposed (component unmount, effect scope stop):
// No manual cleanup needed - handled automatically
const update = useRaf(callback)SSR Safe
The composable is a no-op in non-browser environments. isActive always returns false during SSR.
Functions
useRaf
(callback: (timestamp: DOMHighResTimeStamp) => void) => UseRafReturnScope-disposed safe requestAnimationFrame.