jQuery keypress event wait 0.5 seconds for another user-keypress

社会主义新天地 提交于 2019-12-12 09:43:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!