Here is my debounce function:
function debounce(fn, wait = 1500) {
let timeout;
return function (...args) {
if (timeout) clearTimeout(timeout);
let context = this;
timeout = setTimeout(function () {
fn.apply(context, ...args);
}, wait);
};
}
Here is my method
in the component:
methods: {
onKeyUp() {
if(this.q.length) this.isLoading = true; // show loading spinner
return debounce(() => this.querySearch())()
},
So I have to execute the debounce call with an extra set of ()
which makes sense, because debounce returns a function. Now, if I change it to this:
methods: {
onKeyUp: debounce(function() {
this.querySearch()
})
I don’t understand why this works – debounce
returns a function. I would expect when onKeyUp
is triggered, it would run debounce
– which just returns a function, without ever executing it. Does it implicitly execute the returned function with this syntax? Why?
Also, why does it need to be a non-arrow function in the second example? I know in the first example you want an arrow fn because you want this
to point to the component context, but im unclear why using this key-value syntax breaks that down here.