2

I'm creating an input field where some data should be fetched (by AJAX) and displayed every time the user enters data into that field. However, if the user types several characters, say he types "test" to get all records who contain the string "test", it would not be necessary to do 4 queries after every character pressed, but one query after he stopped typing. I can think of several solutions with a global variable where I check if the same event has been fired again, but is there a really elegant way to do this? Maybe check if there is something in the keyboard buffer and only proceed if it is empty? Or is there an event that is only fired once the keyboard buffer is empty and all characters are in the input field?

  • 1
    Try to set delay before firing an event. Example https://stackoverflow.com/questions/1909441/how-to-delay-the-keyup-handler-until-the-user-stops-typing – Movs Jul 29 '21 at 13:39
  • Does this answer your question? [How to delay the .keyup() handler until the user stops typing?](https://stackoverflow.com/questions/1909441/how-to-delay-the-keyup-handler-until-the-user-stops-typing) – ControlAltDel Jul 29 '21 at 13:41

2 Answers2

0

The elegant way is to use a timeout, and to keep clearing the previous timeout with each key press

var tID;

function keyUp (e) {
  if (tID) clearTimeout(tID);
  tID = setTimeout(function() {
    ... // make web call
  }, 2000);
}

This will ensure that the web call is only called after the last key is pressed (you may want to adjust the timeout value)

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Thanks, that is definitly elegant. Only disadvantage is that I have to let the user wait for the specified time, so the application will "feel" slower to him if he's a fast typer. I won't care too much for additional calls for slow typers, so I'll try with 500 ms. But if there was a solution with the keyboard buffer I would still like it better. – Herbert Pfeifer Jul 31 '21 at 09:06
0

There are ways to achieve this that I can think of:

  1. Use timeout, from the last keyup event. This is not always the best and not that precise with users that have low typing speed.
  2. Use space character do regconize if the user has finished typing a word. Based on changes in length and total word count, you can decide if you would want to send AJAX or not.

Depends on the type of input you are working with, you may choose the most suitable method for you. The first one is somewhat quite rigid. The second method requires user to press space every time he finishs typing. A little bit of both could be a sweet spot perhaps. In modern day, I don't think sending request every keyup will cause huge performance effect though.

Huy Phạm
  • 888
  • 9
  • 24