【问题标题】:debounce function being called every time每次调用 debounce 函数
【发布时间】:2019-04-26 12:20:41
【问题描述】:

我在 keyUp 上调用 searchkeyword 函数。我想在快速输入新字母时取消/clearTimeout $emit,以便只调用几次 $emit。 但是控制台在每次搜索关键字调用时都会被调用/去抖动。

  methods: {
    searchKeyword : function() {
      var scope = this;
      (this.debounce(function(){
        scope.$emit("search-keyword", scope.keyword);
        console.log("Called");
      },350))();
    },
    debounce: function (func, delay) {
        var timeout;
        return function() {
          const context = this;
          const args = arguments;
          clearTimeout(timeout);
          timeout = setTimeout(() => func.apply(context, args), delay);
        }
      }
    }

【问题讨论】:

  • 您必须只调用一次debounce,而不是每次调用searchKeyword

标签: javascript vue.js ecmascript-6 debounce


【解决方案1】:

您的方法很好,设置超时然后清除它是一种众所周知的去抖动方法。这个answer 描述它并使用相同的方法。

问题是您在每次调用searchKeayword 时都会创建一个新的去抖动函数,然后立即执行它。

您需要直接传递去抖函数。

const debounce = (fn, delay) => {
  let timeout;

  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(_ => fn.apply(context, args), delay);
  };
};

new Vue({
  el: '#root',
  name: "App",
  data: _ => ({ called: 0 }),
  methods: {
    doSomething: debounce(function() {
      this.called += 1;
    }, 2000)
  },
  template: `
    <div>
      <button v-on:click='doSomething'>Do Something</button>
      I've been called {{ called }} times
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='root'></div>

还要注意 debounce 不需要是组件的方法。

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2019-04-08
    • 2016-01-30
    • 2020-06-16
    • 1970-01-01
    • 2011-11-06
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多