Here is a custom debounce function I implemented:
function customDebounce(func, delay = 1500) {
let timeout;
return function (...args) {
if (timeout) clearTimeout(timeout);
let context = this;
timeout = setTimeout(function () {
func.apply(context, ...args);
}, delay);
};
}
Within my component, I have a method called onKeyUp
:
methods: {
onKeyUp() {
if(this.q.length) this.isLoading = true; // display loading spinner
return customDebounce(() => this.querySearch())()
},
When it comes to executing the debounce call in a different way:
methods: {
onKeyUp: customDebounce(function() {
this.querySearch()
})
I find it fascinating that in the second example above, the debounced function is executed immediately. This behavior surprises me because typically a debounced function should only execute after a certain delay. Does the syntax used somehow implicitly trigger the execution of the returned function?
Moreover, I'm puzzled by the necessity for the function in the second scenario to be declared as a non-arrow function. While I understand the rationale behind using an arrow function in the first instance to preserve the component's context with this
, I cannot comprehend why the key-value syntax alters this behavior.