BeginnerCoder

Lesson 18 — Watchers with cleanup

Cancel the previous run

A watcher callback gets a third argument, onCleanup. Whatever function you register with it runs right before the next run of the watcher (and when the component goes away). That is the place to cancel the previous timer or request, so only the latest one finishes — this is called debouncing.

watch(q, (value, old, onCleanup) => {
  const ctrl = new AbortController()
  fetch("/search?q=" + value, { signal: ctrl.signal })
  onCleanup(() => ctrl.abort())
})

Why it matters: without cleanup, fast typing fires a search per keystroke and old results can overwrite new ones.

Want it another way?
Task

Register a cleanup that clears the timer. Typing "a" then "ab" quickly should run only one search: "Searches run: 1".

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Vue.js Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.