4

请参阅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);
  };
}

从这里http://remysharp.com/2010/07/21/throttling-function-calls/

介意检查我是否做错了吗?

4

2 回答 2

9

您的代码应如下所示

$('input').keyup( function() {
    console.log('k');
});

$('input').keyup(debounce(f, 100));

在您的示例中,您永远不会调用返回的函数,它总是在创建一个新函数。


根据您的评论。如何在不同的上下文中使用它。以下示例将向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();
}
于 2013-05-22T16:29:14.233 回答
0

你必须调用函数,从返回debounce。将代码更改为

$('input').keyup( function() {
    console.log('k');
    this.func = this.func || debounce(f, 100);
    this.func.apply( this, Array.prototype.slice.call(arguments) ); 
});
于 2013-05-22T17:01:07.620 回答