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.
Register a cleanup that clears the timer. Typing "a" then "ab" quickly should run only one search: "Searches run: 1".
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based Vue.js Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Vue.js Foundations books — check the publication year so the examples match current versions.
Search Amazon →