有几个div和处理程序,当它们被点击时会发送ajax请求。我的问题是我不知道如何强制处理程序不超过每30秒1个请求的限制。
感谢您的帮助!
有几个div和处理程序,当它们被点击时会发送ajax请求。我的问题是我不知道如何强制处理程序不超过每30秒1个请求的限制。
感谢您的帮助!
Underscore.js有一个优秀的节流函数。你传入要节流的处理程序,就会得到一个速率受限制的同一函数的版本。
var throttled = _.throttle(someHandler, 100);
$(div).click(throttled);
http://documentcloud.github.com/underscore/#throttle
这是我在自己的代码中使用的简化版本:
function throttle(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
if (!timeout) {
// the first time the event fires, we setup a timer, which
// is used as a guard to block subsequent calls; once the
// timer's handler fires, we reset it and create a new one
timeout = setTimeout(function() {
timeout = null;
func.apply(context, args);
}, wait);
}
}
}
一个测试它的好方法是触发大量滚动事件并观察您的处理程序记录到Firebug控制台中:document.addEventListener("scroll", throttle(function() {
console.log("test");
}, 2000), false);
以下是一个版本,使用jQuery限制每30秒内只能点击一次div
:
$("div").click(throttle(function() {
// ajax here
}, 30000));
如果您想进行速率限制,那么不幸的是underscore.js提供的_.throttle方法不是您的解决方案。此方法只会确保您的方法在X秒内不会被调用多次,因此所有随后的函数调用都将被忽略,直到该时间段过去。
如果您想对函数进行速率限制,以便每秒钟不要超过X次调用该函数,但又不想完全丢失这些函数调用,则需要完全不同的解决方案。
我编写了一个underscore扩展程序,可以在https://gist.github.com/1084831找到。
您可以在http://jsbin.com/upadif/8/edit#preview上看到一个工作示例。
if ($(this).data('canFireRequest')) {
// Ajax request goes here
$(this).data('canFireRequest', false);
}
setTimeout(function() {
$(this).data('canFireRequest', true)
}, 30000);
_.throttle
通常是您想要的。您排队一堆事件驱动回调以在事件发生后长时间执行的用例是什么? - Wayne