油门AJAX请求的KeyUp和粘贴活动 [英] Throttle AJAX Request On KeyUp and Paste Events
问题描述
所以,我呼吁每一个AJAX请求 KEYUP
和粘贴
事件jQuery中的一个文本框:
So I am calling an AJAX request on every keyup
and paste
event in jQuery on a textbox:
$("#server-label").bind("keyup paste", function() {
$.ajax()...
});
现在的问题是,这是如果用户迅速presses键太多的AJAX请求。是什么样的等待,直到用户停止输入了一点(比如500毫秒)调用Ajax请求之前的最佳方式。基本上不使AJAX请求,直到没有解雇500毫秒键或粘贴事件。
The problem is this is just too many AJAX requests if the user rapidly presses keys. What is the best way to sort of wait until the users stops typing for a bit (say 500ms) before calling the AJAX request. Basically don't make the AJAX request until no keys or paste events fired for 500ms.
感谢。
推荐答案
尝试使用的setTimeout()
和定时器
VAR来跟踪它:
Try using setTimeout()
and a timer
var to keep track of it:
var t;
$("#server-label").on("keyup paste", function() {
clearTimeout(t);
t = setTimeout(function() {
$.ajax({/*[...]*/});
//...
}, 500);
});
您也可以使用油门或去抖但我不想想,如果你换你的code函数对象或字符串中传递给的setTimeout()
功能,它会是必要的。
You can also use throttle or debounce but I don't think it'd be necessary if you wrap your code inside a function object or string to pass to the setTimeout()
function.
这篇关于油门AJAX请求的KeyUp和粘贴活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!