0

I just saw this tutorial about debounce, but very confused about how the name arguments is passed through all these functions in debounce when he use debounceSayHello("Jeremy"). Why debounce(sayHello,3000) instead of debounce(()=>sayHello(name),3000)? And when define the inner returned anonymous function, there's no arguments there, how did the 'Jeremy' is passed in and finally get to the apply function? Thank you so much!

function debounce (func, delay) {
  let timerId;
  return function () {
    if (timerId) {
      clearTimeout(timerId)
    }
    timerId=setTimeout(()=>func.apply(this,[...arguments]),delay);
  }
}

function sayHello(name){
 console.log(`Hello ${name}`);
}

let debouncedSayHello=debounce(sayHello,3000);

debouncedSayHello('Jeremy')





//Hello Jeremy

Original:

https://www.youtube.com/watch?v=qwbjDkSqgss

1
  • sayHello(name) would call the function right then and there and execute it and send what the method returns. Dec 18, 2019 at 16:56

1 Answer 1

1

Arguments is an Array-like object accessible inside function that contains the values of the arguments passed to that function.

 function sumTotal(){
      console.log(arguments); // {'1':1,'2':2,'3':3,'4': 4}
      var numSet = [...arguments];
      return numSet.reduce((total, num)=>total+num);
    }

 console.log('Sum: ', sumTotal(1,2,3,4));//Sum: 10
3
  • Ah Thank you so much! So when we define a function, like "function sumTotal()", even we don't define it like "function sumTotal(num1, num2) {}", when we call the function with arguments, if we use "arguments" inside it will still work with all the arguments we passed in right? Thank you so much! So for the debounce function, is it correct that: when we use debounce('sayHello',3000), we actually store the returned function "function() {if(timeId....) timeId=...func.apply(this,[...arguments])}" to the debounceSayHello, then we actually called the returned function with the 'Jeremy'..
    – Ying
    Dec 18, 2019 at 16:52
  • And even it's not defined with arguments, our 'Jeremy' will go to the [...arguments] and so we can use apply to call the SayHello with this 'Jeremy' right? Thank you so much!!!:D
    – Ying
    Dec 18, 2019 at 16:53
  • arguments is special object inside function it keep store the arguments inside it which is passed to function.
    – OSCURO
    Dec 18, 2019 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.