我正在向服务器发送ajax请求,用户输入< input>元素,像这样:
$('#my-input').bind("input", function(event){
// here's the ajax request
});
困扰我的是它在每个用户的密钥上发送了不必要的许多请求,这意味着如果用户输入速度非常快,则会有许多不必要的请求.所以我认为应该有一定的延迟/超时,等待一段时间(50毫秒?)让用户在发送ajax请求之前停止输入.那将是一个问题解决了.
但是,在发送另一个请求之前第一个ajax请求尚未完成的情况呢? (键入60 ms / char,而ajax请求需要300 ms).
解决方法:
您可以在下划线库中使用throttle函数.正如其文件所述:
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
即使您不想引入新库,您仍然可以从source code中了解此函数的工作原理.事实上,简单版本的节流函数可能是:
function throttle(func, delay) {
var timeout = null;
return function() {
var that = this, args = arguments;
clearTimeout(timer);
timeout = setTimeout(function() {
func.apply(that, args);
}, delay);
};
}
这个jQuery throttle-debounce plugin也很有帮助.特别是,根据作者的说法,去抖功能似乎比油门功能更适合您的需要:
Debouncing can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。