Sub topic 4
When to ask: triggering, debouncing and cancelling requests
This chapter assumes you can read TypeScript or Python, know that an editor calls extension code on events, and understand that a model request takes noticeable time. Context assembly and fill-in-the-middle prompts are covered in earlier chapters.
Why timing matters
An editor assistant cannot send a request on every keystroke without cost. A fast typist produces several characters per second, and each request uses compute, network and money. Most of those requests would return text for a cursor position that no longer exists.
Three controls keep the feature responsive:
- Triggering decides which events start a request at all.
- Debouncing waits until typing pauses before sending.
- Cancellation abandons a request once its result is stale.
Triggering
Editors usually distinguish two kinds of trigger.
- Automatic: the user types or moves the cursor, and the editor asks the provider for items.
- Explicit: the user presses a shortcut to request a suggestion on demand.
Automatic triggers should skip positions where a suggestion is unlikely to help. Common skips are a cursor in the middle of a word, a file type the feature does not support, a very large file, or a position where a suggestion is already showing and still matches what the user typed.
Debouncing
Debouncing delays the request until no new keystroke has arrived for a short interval, often 75 to 300 ms. Each new keystroke restarts the wait. Only the last position in a burst of typing sends a request.
The delay is a trade-off. A longer wait sends fewer requests but adds to the time before a suggestion appears. A shorter wait feels faster but wastes more requests.
import asyncio
class Debouncer:
def __init__(self, delay: float) -> None:
self.delay = delay
self._task: asyncio.Task | None = None
def call(self, coro_fn):
"""Schedule coro_fn after the delay, replacing any pending call."""
if self._task and not self._task.done():
self._task.cancel()
self._task = asyncio.ensure_future(self._run(coro_fn))
async def _run(self, coro_fn):
await asyncio.sleep(self.delay)
await coro_fn()
async def main():
debouncer = Debouncer(0.15)
async def request(label: str):
print("request for", label)
for text in ["d", "de", "def"]:
debouncer.call(lambda t=text: request(t))
await asyncio.sleep(0.05) # typing faster than the delay
await asyncio.sleep(0.4)
asyncio.run(main())Only request for def prints, because each earlier call is cancelled before its delay ends.
Cancelling stale requests
Debouncing cannot help once a request is in flight. If the user keeps typing, the response will describe an old cursor position. The extension should cancel it for two reasons: to avoid showing a wrong suggestion, and to free the backend, which may stop generating tokens when the connection closes.
In VS Code, the provider receives a CancellationToken. The example in the Topic Spine's extension code connects it to an AbortController, so cancelling in the editor aborts the HTTP request. The same example also checks token.isCancellationRequested after its delay, which skips the request entirely if the user has already moved on.
placeholderCommon errors
- Showing stale results. A response arrives for an old cursor position and is displayed anyway. Compare the response's document version and position with the current ones before showing it.
- Cancelling only in the editor. The editor drops the result, but the HTTP request keeps running. Pass the abort signal to the network call.
- A fixed delay for everything. A delay tuned for slow typing makes explicit requests feel sluggish. Skip the delay when the user triggers a suggestion by shortcut.
- Swallowing abort errors. An aborted
fetchthrows. Catch it and return an empty list instead of logging an error for every cancelled request.
Exercise
A user types quickly, pausing 100 ms between characters, and your debounce delay is 150 ms. How many requests are sent for a burst of 10 characters, followed by a long pause? What changes if you lower the delay to 50 ms?
Show answer
With a 150 ms delay, each pause is shorter than the delay, so the timer restarts every time and one request is sent, after the last character. With a 50 ms delay, the timer ends during each 100 ms pause, so a request is sent after every character, about 10 requests. Each of the first nine would then be cancelled if the next keystroke arrives while it is in flight.