0

I'm not understanding the debounce return, I understand about the rest and spread operator but my question is, when I console.log(...args) it's related to input event but how return receives it ?

    const fetchData = async (searchTerm) => {
  const response = await axios.get('http://www.omdbapi.com/', {
    params: {
      apikey: '',
      s: searchTerm,
    },
  });
  console.log(response.data);
};

const input = document.querySelector('input');

const debounce = (func) => {
  let timeoutId;

  return (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func.apply(null, args);
    }, 2000);
  };
};

const onInput = debounce((event) => {
  fetchData(event.target.value);
});
input.addEventListener('input', onInput);

Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40
  • "*return receives it?*" - this has nothing to do with the `return` keyword. It's a function expression, and functions receive their arguments when being called (here: as an event handler). – Bergi Nov 07 '20 at 11:46
  • Sorry, I'm a begginer, thanks for helping :) But I don't understand how it's been passed the arguments to the return function expression. I've searched that ever callback event receives an event as argument, but when it's passed as an argument the (...args)? – juicefruit Nov 07 '20 at 12:00
  • In an `onInput(e)` call. Which the browser does for you when an input event on the input happens. – Bergi Nov 07 '20 at 12:06
  • You could also write `input.addEventListener('input', event => onInput(event));` to make it more clear maybe – Bergi Nov 07 '20 at 12:06
  • Can you help me with the execution flow at the first and second time someone digit a letter please? – juicefruit Nov 07 '20 at 12:23
  • 1
    Related: [Can someone explain the “debounce” function in Javascript](https://stackoverflow.com/q/24004791) – VLAZ Nov 07 '20 at 12:24

0 Answers0