首页 > 解决方案 > Javascript Debounce 没有从 vue 组件中清除它的队列

问题描述

我正在使用这里的去抖方法https://www.freecodecamp.org/news/javascript-debounce-example/

function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}
function saveInput(){
  console.log('Saving data');
}
const processChange = debounce(() => saveInput());

我想包含在我们拥有的图书馆中,所以common.js我有:

export default {
  otherStuff,
  debounce(func, timeout = 300) {
    let timer;
    return (...args) => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(this, args);
      }, timeout);
    };
  },

在 vue.js 我有一个文本框有一个事件@keyup="searchboxChange()"

在方法部分:

import common from "@/assets/js/Service/Common";
... stuff removed for brevity
methods:
  {
    searchboxChange(){
      common.debounce(() => this.filterChanged(), 1000)();
    },
  }

我必须在 debounce 方法的末尾包含 () 否则它实际上并没有触发。然而,虽然它完美地去抖动,但当超时到期时,每个事件都会被触发。this.filterChanged()因此,如果我的搜索是“HELLO”,我会看到 5 个请求在被调用 5 次的同时被触发。

我确信超时变量的范围很简单,因为在 debounce 方法中添加一个 console.log 表明每次都未定义计时器。

标签: javascriptscopedebounce

解决方案


您需要对组件方法进行去抖,否则您将从组件方法中调用多个去抖函数。

像这样的东西应该工作

methods: {
  // ...
  searchboxChange: common.debounce(function() {
    this.filterChanged();
  }, 1000)
}

注意与function短函数语法相对的使用。您需要这样做以确保正确的词法范围this


推荐阅读