nathancahill / Anycomplete

The magic of Google Autocomplete while you're typing. Anywhere.
1.54k stars 49 forks source link

Debounce requests by using a timer, to avoid one request per key stroke. #12

Closed nfvs closed 8 years ago

nfvs commented 8 years ago

The current code makes one request for every keystroke, which can be too much.

This PR starts a timer (default 0.3 seconds, although that can be made customizable) and will only make the request once this timer finishes (every keystroke cancels the previous timer and starts a new one).

The diff can be hard to read because of indentation, but it basically takes all the code inside queryChangedCallback() and moves it inside the timer callback.

There's also a commented-out alert to display the string being sent in the request, for debugging.

nathancahill commented 8 years ago

Why do you say every keystorke can be too much? I'm interested in implementing a debounce, but I think 0.3 is too slow.

nfvs commented 8 years ago

Why do you say every keystroke can be too much?

Because for your screenshot example in the README, even if you only write aurora, you'll trigger 6 separate HTTP requests: a, au, aur, auro, etc. You'll be making one request per character, in my view unnecessarily.

Not to mention that it's kind of a race condition since the response for aurora may for some reason take longer to arrive than the one for auror (or any other for that matter), so in that case you'll get results not from the latest one, but from the request whose response arrived last.

I tried 0.3s and even then it fired some requests before I had stopped typing, but let me know of a value and I can change it. I'd recommend you try it first though, since I found 0.3 on the too-fast side of the scale.

nathancahill commented 8 years ago

That happens in Google too. The point of autocomplete is that it happens while your typing, not when you finish. So I think for now I'm going to keep the behavior as is.