JQuery keypress event wait 0.5 second for another keypress

I am currently developing a direct search for my website and want to reduce unnecessary query with simple jQuery (of course, I have stream-stream control). I have a keydown-event-listener for my search field. This currenty listener only runs the ajax command for the php lookup function if val (). Length is> = 3.

But now I want an additional condition. Therefore, when length> = 3, I want to wait about 0.5 s or so if the user performs another click. If he does, the function should not be called, and I want the listener to wait another 0.5 seconds and wait again for more user input and so on. How to implement such a function?

+3
source share
1 answer
var timeout;

$('#yousearchbox').on('keyup',function(){
  //if you already have a timout, clear it
  if(timeout){ clearTimeout(timeout);}

  //start new time, to perform ajax stuff in 500ms
  timeout = setTimeout(function() {
   //your ajax stuff
  },500);
})
+9
source

All Articles