Aen*_*Tan 4 javascript debouncing
请参阅http://jsfiddle.net/5MvnA/2/和控制台.
Fs应该少于Ks,但根本没有Fs.
我得到了去抖动代码
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
Run Code Online (Sandbox Code Playgroud)
从这里http://remysharp.com/2010/07/21/throttling-function-calls/
请注意我是否做错了?
您的代码应如下所示
$('input').keyup( function() {
console.log('k');
});
$('input').keyup(debounce(f, 100));
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您永远不会调用返回的函数,并且它始终在创建一个新函数.
根据您的评论.如何在不同的上下文中使用它.以下示例将向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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10457 次 |
| 最近记录: |