0

I'm building a custom search engine for a website and the search is done via AJAX on keyup event, so when you start typing ( if you type more than two characters and after the string is trimmed ) an AJAX call to the server is done.

It works perfectly, but there's one scenario I was thinking about, when you start typing four or as many as you want characters in a row, there will be as many calls as characters you type. Well that's going to make a lot of requests if you type 10 characters for instance.

In this case I was thinking if there is a simple way of stopping everything what was started before when such behavior occurs and pick up the search after you're done typing insanely (:

Roland
  • 9,321
  • 17
  • 79
  • 135

3 Answers3

1

Simply delay the call via Ajax until they have not typed anything for .5 to 1 second. Then you can simply cancel a setTimeout etc.

-- @Tejs

Phil H
  • 19,928
  • 7
  • 68
  • 105
  • That was my first though too (: But I wanted to be sure that there isn't any fancy method out there that could make things easier and better (: – Roland Oct 30 '12 at 15:37
  • Not really... you can't cancel the request after it has gone, so you will have to wait to some degree. You could conceivably send the first request, but then if a second key is pressed quickly, wait until 0.5s after the last key has been pressed and send the next request. – Phil H Oct 30 '12 at 15:46
1

You can use Underscore debounce for that. Make the key up event call undersocre's function instead of your function, that way underscore will know when to call your function.

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • 1
    @roasted Well... if you want to use Underscore *only* for that, then you may preffer making your small startTimeout-wait-cancelTimeout logic, but then you're doing 2 things: a) You're writing durty code (yes, starting and canceling a timeout isn't *that* clean.) And b) You're wasting your time. Underscore can help you with a lot of stuff in JS. Just have a look at the docs and you'll see how less code you'll need to write. – alexandernst Oct 30 '12 at 15:40
  • This approach sounds good, but then I have to include another library just to add this functionality (: – Roland Oct 30 '12 at 15:40
  • I just did Alexander (: Thanks for the input – Roland Oct 30 '12 at 15:42
  • Alexander, I'm binding the _.debounce function to the function I want to execute with delay, but it seems like it doesn't respond to the delay ... – Roland Oct 30 '12 at 16:17
0

As been said before, here's an example that executes a function after a certain specified delay, and if the method is called again when the delay hasn't passed the original timeout is cleared and a new one is set again.

This is a clean solution and it doesn't require jQuery, just alter the usage.

How to delay the .keyup() handler until the user stops typing?

Community
  • 1
  • 1
andy
  • 531
  • 5
  • 16