简体   繁体   中英

Why do I have to use a high order function as first argument in setTimeout?

I have the following code:

HTML:

<button class="clickMe">Click Me</button>

JS:

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

const debounce = (fn, delay) => {
  let timeoutId;
  return function(...args) {
    if(timeoutId) {
      clearTimeout(timeoutId);
    } 
      timeoutId = setTimeout(() => {
        fn(...args)
      }, delay)
  }
}

clickMe.addEventListener('click', debounce((e) => {
  console.log('clicked')
}, 300));

On this line:

timeoutId = setTimeout(() => {
        fn(...args)
      }, delay)

I've tried to pass the fn(...args) directly in like this:

timeoutId = setTimeout(fn(...args), delay)

But that doesn't work. Why is that we need a higher order function that returns that inner function here?

Actually you don't need that wrapping up of your function call inside another anonymous function. You can make use of the following syntax:-

timeoutId = setTimeout(func, delay,...args);

Also that's not a higher order function . A higher order function can either accept a function as argument or return a function or do both. You can say setTimeout is a higher order function .

For more info on this syntax, look up - https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM