我有一个复选框不是可以切换某种行为,但是,如果有人做100个连续的点击我不想100请求发送到我的服务器端。
I have a checkbox than can toggle certain behaviour, however if someone makes a 100 consecutive clicks I don't want to send 100 requests to my server side.
这是我在的地方得那么远(发现这个code段):
This is what I got in place so far (found this code snippet):
deBouncer = function($,cf,of, interval){
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
}
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || interval);
}
}
jQuery.fn[cf] = function(fn){ return fn ? this.bind(of, debounce(fn)) : this.trigger(cf); };
};
在我的文档准备功能:
deBouncer(jQuery,'smartoggle', 'click', 1500);
那么事件本身:
Then the event itself :
$(window).smartoggle(function(e){
MyToggleFunction();
});
这个工程,我已经把1500毫秒是去抖周期,因此,如果你点击了n次withing 1500毫秒,将只发送最新的状态到服务器。
This works as I've put 1500 ms to be the debouncing period, so if you click n times withing 1500 ms it will send only the latest state to the server.
然而,有采用这种副作用,现在我的单击事件其他的东西被弄乱了。难道我做错了什么吗?有没有更好的办法去抖?
There is however side effect of using this, now my click event for other stuff is messed up. Am I doing something wrong here? Is there a better way to debounce?
不知道是否有可能是一个正确的方式做到这一点。
Not sure if there can be a "proper" way to do this.
说到这里强调有这样一个实用工具,将创建功能抖版本...
Having said that underscore has such a utility that will create a debounced version of your function...
var MyToggleDebounced = _.debounce(MyToggleFunction, 1500);
然后用 MyToggleDebounced
在单击处理程序。
链接抖上underscorejs文档
看看注释的源代码,他们是如何做到这一点。
Take a look at the annotated source for how they do it.