Hey programmers, I have removed everything from my function below to just target exactly what I need help with...
嘿,程序员们,我已经从下面的函数中删除了所有东西,只针对我需要的帮助……
After the keyup event is called, the reloadContent function will make an ajax call to gather new data from a database.
在调用keyup事件之后,reloadContent函数将调用ajax从数据库中收集新数据。
Only problem is, my servers are overloading because there is no delay from the keyup events, after every keyup the function is called.
唯一的问题是,我的服务器正在重载,因为在每次调用keyup函数之后,keyup事件没有延迟。
I need a way to delay, say 1 second, before the reloadContent function is called. This way it will not run 4 times (when the user types in j o h n) but only 1 time after the user types (john), assuming they can type more than 1 character/sec.
在调用reloadContent函数之前,我需要一种延迟的方法,比如1秒。这样,它将不会运行4次(当用户在john中输入时),而是在用户类型(john)之后运行1次,假设他们可以输入超过1个字符/秒。
$('#searchinput').live('keyup',function() {
reloadContent(); //execute load function
});
Any advice is appreciated
任何建议都是赞赏
2 个解决方案
#1
6
You can set a timeout in your keyup
handler and use jQuery's data() facility to associate its id with the element. That way, if the keyup
event is triggered again before the delay runs out, you can clear the existing timeout and schedule a new one:
您可以在keyup处理程序中设置一个超时,并使用jQuery的data()工具将其id与元素关联。这样,如果在延迟结束之前再次触发keyup事件,您可以清除现有的超时并安排一个新的超时:
$("#searchinput").live("keyup", function() {
var $this = $(this);
var timerId = $this.data("timerId");
if (timerId) {
window.clearTimeout(timerId);
}
$this.data("timerId", window.setTimeout(reloadContent, 1000));
});
#2
1
$('#searchinput').live('keyup',function() {
window.setTimeout(function(){
reloadContent(); //execute load function
},1000);
});
This will make a delay, but I think you need not only delay to make what you want.
这将会造成延迟,但我认为你不仅需要延迟来实现你想要的。
#1
6
You can set a timeout in your keyup
handler and use jQuery's data() facility to associate its id with the element. That way, if the keyup
event is triggered again before the delay runs out, you can clear the existing timeout and schedule a new one:
您可以在keyup处理程序中设置一个超时,并使用jQuery的data()工具将其id与元素关联。这样,如果在延迟结束之前再次触发keyup事件,您可以清除现有的超时并安排一个新的超时:
$("#searchinput").live("keyup", function() {
var $this = $(this);
var timerId = $this.data("timerId");
if (timerId) {
window.clearTimeout(timerId);
}
$this.data("timerId", window.setTimeout(reloadContent, 1000));
});
#2
1
$('#searchinput').live('keyup',function() {
window.setTimeout(function(){
reloadContent(); //execute load function
},1000);
});
This will make a delay, but I think you need not only delay to make what you want.
这将会造成延迟,但我认为你不仅需要延迟来实现你想要的。