javascript 去抖动不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16696873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Debouncing not working
提问by Aen Tan
See http://jsfiddle.net/5MvnA/2/and console.
请参阅http://jsfiddle.net/5MvnA/2/和控制台。
There should be less Fs than Ks but there are no Fs at all.
Fs 应该比 Ks 少,但根本没有 Fs。
I got the debouncing code
我得到了去抖动代码
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
from here http://remysharp.com/2010/07/21/throttling-function-calls/
从这里http://remysharp.com/2010/07/21/throttling-function-calls/
Mind checking if I'm doing it wrong?
介意检查我是否做错了吗?
回答by epascarello
Your code should look like this
你的代码应该是这样的
$('input').keyup( function() {
console.log('k');
});
$('input').keyup(debounce(f, 100));
In your example, you are never calling the function returned and it is always making a new function.
在您的示例中,您永远不会调用返回的函数,它总是在创建一个新函数。
Based on your comment. How to use it in a different context. The following example will write foo
10 times to the console, but will only add one timestamp.
根据您的评论。如何在不同的上下文中使用它。以下示例将向foo
控制台写入10 次,但只会添加一个时间戳。
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
function fnc () {
console.log("Date: ",new Date());
}
var myDebouncedFunction = debounce(fnc, 100);
function foo() {
console.log("called foo");
myDebouncedFunction();
}
for ( var i=0; i<10; i++) {
foo();
}
回答by rab
You have to call function , returns from debounce
. change code to
你必须调用函数,从debounce
. 将代码更改为
$('input').keyup( function() {
console.log('k');
this.func = this.func || debounce(f, 100);
this.func.apply( this, Array.prototype.slice.call(arguments) );
});