0

While learning about Debounce in JS, I've seen 2 different approaches. Is there a difference between calling the callback within the function declaration example vs calling with apply binding within the arrow function example?

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

VS

function debounce(func, delay){
   let timeoutId;
   return (...args) => {
       clearTimeout(timeoutId);
       timeoutId = setTimeout(() => {
          func.apply(this, args);
       }, delay);
   };
}
Brandi
  • 161
  • 1
  • 10
  • those are not the same functionality. And that second one does no debouncing.... – epascarello May 03 '23 at 17:14
  • oops, sorry I just edited it! – Brandi May 03 '23 at 17:34
  • Is your question about the difference between arrow functions and functions declared using the `function` keyword? See https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable for instance. – Guillaume Brunerie May 03 '23 at 17:40
  • I'm trying to confirm whether they are identical in all use cases, or is one flawed (returning the function declaration, probably). If both examples are the same, I guess I want to really look at it to figure how they're the same. – Brandi May 05 '23 at 02:25
  • 1
    They are not equivalent. `func.apply(this, args)` is obviously different from `cb(args)` (which should've been `cb(...args)` btw) in the presence of a non-`undefined` value of `this`. – Bergi May 05 '23 at 02:36

0 Answers0