Utilities · @vueuse/shared v15.0.0 · Reviewed

Debounce search and autosave with useDebounceFn

Wait until someone stops typing (or clicking, or resizing), then run your function once.

App.vueVue SFCOpen in Vue Playground ↗
Live preview

Edit the code and the preview updates as you type.

What it does

Some events fire many times a second: typing, resizing, scrolling. If each one sends an API request, typing one word can send ten. A debounced function waits for a pause, say 400 ms with no new calls, then runs once with the latest arguments.

useDebounceFn wraps any function in that behaviour. Call the wrapped version as often as you like. It returns a promise that resolves with your function's result once it finally runs.

The code

Vue · Composition API
import { useDebounceFn } from '@vueuse/core'

const saveDraft = useDebounceFn((text) => {
  return $fetch('/api/draft', { method: 'POST', body: { text } })
}, 500)

// call it on every keystroke; it runs 500ms after the last one
saveDraft(text)

Where you'd use it

  • Search-as-you-type without sending a request per key
  • Autosaving a draft or a settings form
  • Checking if a username or coupon code is valid while someone types
  • Recalculating a layout after the window stops resizing

Real-world example: product search as you type

Typing “laptop” can produce seven input events. Debouncing waits for a pause before starting one request with the latest query. It reduces request frequency, but it does not abort a request that has already started or prevent responses arriving out of order.

Debounce or throttle?

ToolTimingTypical use
useDebounceFnRun after input pausesSearch requests, autosave
useThrottleFnRun at most once per interval while input continuesScroll and resize work
refDebouncedExpose a delayed ref valueReactive search query
watchDebouncedDebounce a watcher callbackReact to changes with a watcher
watchThrottledThrottle a watcher callbackLimit reactive side effects

Production search: cancel stale requests

const query = ref('')
const results = ref([])
const loading = ref(false)
const errorMessage = ref('')
let controller
let latestRequest = 0

const search = useDebounceFn(async (term, requestId) => {
  controller = new AbortController()
  loading.value = true
  errorMessage.value = ''
  try {
    results.value = await $fetch('/api/search', {
      query: { q: term }, signal: controller.signal,
    })
  } catch (error) {
    if (error.name !== 'AbortError' && requestId === latestRequest)
      errorMessage.value = 'Search failed. Try again.'
  } finally {
    if (requestId === latestRequest) loading.value = false
  }
}, 300, { maxWait: 1500 })

function onSearchInput(event) {
  query.value = event.target.value
  const requestId = ++latestRequest
  controller?.abort()
  if (!query.value.trim()) {
    search.cancel(); results.value = []; loading.value = false; errorMessage.value = ''
    return
  }
  search(query.value, requestId)
}

Bind the input to onSearchInput and show loading, errorMessage and results in the template. Incrementing the request id on every keystroke invalidates an in-flight response even during the debounce delay; clearing input cancels pending work immediately. For a reactive Nuxt query, debounce the value with refDebounced and pass it to useFetch. The debounced function exposes cancel(), flush() and isPending; flush pending work before navigation if you must save it. Cancel pending work when its context disappears.

Do not use debounce as payment protection. Disable the submit button while processing and enforce idempotency on the server.

In Nuxt (and other gotchas)

With Nuxt's useFetch, debounce the value, not the function. useFetch refetches by itself when a reactive query changes, so give it a debounced ref with refDebounced:

const q = ref('')
const debouncedQ = refDebounced(q, 300)
const { data } = await useFetch('/api/search', { query: { q: debouncedQ } })

Autosave tip: if someone types without ever pausing, a plain debounce never fires. Add { maxWait: 2000 } as the third argument so it saves at least every two seconds.

It's SSR-safe: timers only start when the function is called. Cancel a pending callback on unmount or when its input context becomes invalid. The returned function exposes cancel(), flush() and an isPending ref for a waiting state.

When not to use it

When you need updates while something is happening, like tracking scroll position or dragging, use useThrottleFn. It runs at most once every N milliseconds instead of waiting for a pause.

To stop double payments, disable the button while the request is running. Debouncing a "Pay" button just delays the second click.

If what changes is a ref, refDebounced or watchDebounced reads more naturally than wrapping a function.

Links

Need a hand with your Vue or Nuxt app?

Related functions