每次都调用 debounce 函数
debounce function being called every time
我在 keyUp 上调用 searchkeyword 函数。我想在快速输入新字母时 cancel/clearTimeout $emit,这样 $emit 只会被调用几次。
但是控制台在每次搜索关键字调用时都是 called/debounce。
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);
}
}
}
你的方法很好,设置超时然后清除它是一种众所周知的去抖动方法。这个answer描述了它,用的是同样的方法。
问题是您在每次调用 searchKeayword
时都创建了一个新的去抖动函数,然后立即执行它。
您需要直接传递 debounced 函数。
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 不需要是组件的方法。
我在 keyUp 上调用 searchkeyword 函数。我想在快速输入新字母时 cancel/clearTimeout $emit,这样 $emit 只会被调用几次。 但是控制台在每次搜索关键字调用时都是 called/debounce。
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);
}
}
}
你的方法很好,设置超时然后清除它是一种众所周知的去抖动方法。这个answer描述了它,用的是同样的方法。
问题是您在每次调用 searchKeayword
时都创建了一个新的去抖动函数,然后立即执行它。
您需要直接传递 debounced 函数。
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 不需要是组件的方法。