Javascript 每次都调用去盎司函数

Javascript 每次都调用去盎司函数,javascript,vue.js,ecmascript-6,debounce,Javascript,Vue.js,Ecmascript 6,Debounce,我正在调用keyUp上的searchkeyword函数。我想在快速键入新字母时取消/clearTimeout$emit,以便只调用几次$emit。 但每次调用searchkeyword时都会调用/取消对控制台的锁定 methods: { searchKeyword : function() { var scope = this; (this.debounce(function(){ scope.$emit("search-keyword", s

我正在调用keyUp上的searchkeyword函数。我想在快速键入新字母时取消/clearTimeout$emit,以便只调用几次$emit。 但每次调用searchkeyword时都会调用/取消对控制台的锁定

  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);
        }
      }
    }

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

问题在于,您在每次调用
searchKeayword
时都会创建一个新的取消公告函数,然后立即执行它

相反,您需要直接传递去抖动函数

const debounce=(fn,延迟)=>{
让超时;
返回函数(){
const context=this;
常量args=参数;
clearTimeout(超时);
timeout=setTimeout(=>fn.apply(上下文,参数),延迟);
};
};
新Vue({
el:'根',
名称:“应用程序”,
数据:=>({调用:0}),
方法:{
剂量:去盎司(函数(){
这被称为+=1;
}, 2000)
},
模板:`
做点什么
我已经被叫过{{{被叫过}}次了
`
})

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