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.
我正在为我的网站开发一个实时搜索,我想用一些简单的jQuery减少一些不必要的请求(当然我有一个后端泛洪控制)。我的搜索字段有一个keydown-event-listener。如果val()。length> = 3,则此侦听器currenty仅触发php搜索功能的ajax命令。
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?
但现在我想要一个额外的条件。因此,当长度> = 3时,如果用户正在执行另一次按键,我想等待约0.5秒左右。如果他这样做,则不应该调用该函数,并且我希望监听器再等待0.5秒并再次等待更多用户输入,依此类推。我如何实现这样的功能?
1 个解决方案
#1
9
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);
})
#1
9
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);
})