另一个用户按键jQuery按键事件等待0.5秒 [英] jQuery keypress event wait 0.5 seconds for another user-keypress

查看:109
本文介绍了另一个用户按键jQuery按键事件等待0.5秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的网站开发一个实时搜索,我想用一些简单的jQuery减少一些不必要的请求(当然我有一个后端泛洪控制)。我的搜索字段有一个keydown-event-listener。如果val()。长度> = 3,则此侦听器currenty仅触发php搜索函数的ajax命令。

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.

但是现在我想要一个额外的条件。因此,当长度> = 3时,如果用户正在执行另一次按键,我想等待大约0.5秒左右。如果他这样做,则不应该调用该函数,并且我希望监听器再等待0.5秒并再次等待更多用户输入,依此类推。我如何实现这样的功能?

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?

推荐答案

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);
})

这篇关于另一个用户按键jQuery按键事件等待0.5秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆