首页 > 解决方案 > 自定义去抖动功能不适用于匿名函数

问题描述

我正在尝试创建一个自定义去抖动功能:

const debounced = [];

const cancelFunc = timeout => () => {
  clearTimeout(timeout);
};

function debounce(fn, wait, ...args) {  
  let d = debounced.find(({ func }) => func === fn);

  if (d) {
    d.cancel();  
  } else {
    d = {};
    debounced.push(d);
  }

  d.func = fn;   
  d.timeout = setTimeout(fn, wait, ...args);
  d.cancel = cancelFunc(d.timeout);
}

如果我使用命名函数,它会按预期工作:

debounce(foo, 1000); // called once with 5 clicks in 1 second

但我无法让它与匿名函数一起使用:

debounce(() => { foo(5); }, 1000); // called 5 times with 5 clicks in 1 second

我在这里创建了一支笔:https ://codepen.io/anon/pen/gQvMdR?editors=1011

标签: javascriptanonymous-function

解决方案


发生这种情况是因为您的find情况。让我们备份,并考虑这段代码:

if (
    (function(){ return 1 }) === (function(){ return 1 })
) {
    console.log('The functions are equal');
} else {
    console.log('The functions are NOT equal');
}

// logs 'The functions are NOT equal'

尽管我写了两个相同的匿名函数,但它们并不严格相等。当您传入该匿名函数时,这实际上就是您正在做的事情。因此,当您在数组中搜索先前找到的函数时,它永远不会找到匹配项,因为每次debounce(() => { foo(5); }, 1000);调用它都会创建一个新函数。由于它永远找不到匹配项,因此永远不会被取消。


推荐阅读