宣布不起作用

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/

请注意我是否做错了?

epa*_*llo 9

您的代码应如下所示

$('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)

  • 所以:_.debounce返回一个函数但不执行它.您只能调用_.debounce一次.如果要多次调用debounced函数,则必须存储函数的_.debounce包装版本并调用此存储版本.(这些是我从这个帮助我的答案中吸取的教训) (3认同)