1

I'm calling searchkeyword function on keyUp. I want to cancel/clearTimeout $emit when new letter is typed quickly, so that only few times $emit is called. But console being called/debounce on every searchkeyword call.

  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);
        }
      }
    }
user2216267
  • 491
  • 3
  • 8
  • 21

1 Answers1

2

You approach is good, setting a timeout then clearing it is a well known approach to debouncing. This answer describes it and uses the same method.

The problem is that you are creating a new debounced function in each call to searchKeayword, then executing it right away.

You instead need to pass the debounced function directly.

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>

Note also that debounce does not need to be a method of your component.

ichigolas
  • 7,595
  • 27
  • 50