问题
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?
回答1:
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);
})
来源:https://stackoverflow.com/questions/21781827/jquery-keypress-event-wait-0-5-seconds-for-another-user-keypress