Currently, I am immersed in a Javascript course and grappling with the intricacies of the code snippet provided below. While I have a solid grasp on most aspects of it, I find myself struggling to follow and comprehend the logic flow within the code, especially concerning the event objects. It is crucial for me to clarify these concepts before proceeding further.
Interestingly, another individual has articulated a similar query here, but unfortunately, I am unable to derive any meaningful insights from the responses shared.
Here's the current extent of my comprehension:
When a key is pressed -> The debounce
function is invoked (and executed) with parameters func
and delay
. In this scenario, the func
parameter refers to the onInput
function (which, as per my understanding, automatically receives an event object when the addEventListener
is triggered).
However, the onInput
function is encapsulated within the debounce
function with func.apply(null, args);
. This raises a perplexing question regarding the creation and propagation of event objects throughout the code execution when keys are pressed.
Subsequently, my primary query revolves around where or how does return (...args)
in the debounce
function obtain its spread parameters?
Doesn't the debounce
function receive the event object instead of onInput
in this instance? If that is the case, then how does onInput
access the event object?
Below is the snippet in question:
const fetchData = async (searchTerm) => {
const response = await axios.get('http://www.omdbapi.com/', {
params: {
apikey: '6459bge8',
s: searchTerm
}
});
console.log(response.data);
};
const input = document.querySelector('input');
const debounce = (func, delay) => {
let timeoutId;
//What is the source of values for ...args?
return (...args) => {
console.log(args);
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func.apply(null, args);
}, delay);
};
};
const onInput = (evt) => {
fetchData(evt.target.value);
};
input.addEventListener('input', debounce(onInput, 500));
Furthermore, I am befuddled when I comment out the code inside the returned function like so:
const debounce = (func, delay) => {
let timeoutId;
return (...args) => {
console.log(args);
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
// timeoutId = setTimeout(() => {
// func.apply(null, args);
// }, delay);
};
};
In such a scenario, the passed-in func
never executes, yet the console displays InputEvents
upon pressing a key, indicating that the args originate from elsewhere rather than being set by func.apply(null, args);
?