Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery keypress event wait 0.5 seconds for another user-keypress

I'm currently developing a live search for my website and I want to decrease some unnecessary request with some simple jQuery (of course I have a back-end-flood-control). I've got a keydown-event-listener for my search-field. This listener currenty only fires the ajax command for the PHP search-function if val().length is >= 3.

But now I want an additional condition. So when the length is >= 3, I want to wait for about 0.5s or so if the user is performing another keypress. If he does, the function should not be called and I want the listener to wait another 0.5s and wait again for more user-input, and so on. How do I realize a function like that?

like image 934
user2655665 Avatar asked Dec 19 '22 18:12

user2655665


1 Answers

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);
})
like image 158
Mild Fuzz Avatar answered Apr 06 '23 19:04

Mild Fuzz