Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

461
Views
Accessing arguments within a callback (javascript)

I'm trying to write a "debounce" function, and I'm stuck in one segment of the code. In the code below, I pass a callback into addEventListener and I wrap it in a debounce function.

This function will have more functionality later, but for now, I just want it to return a function, that will set a timeout for delay milliseconds and then call the original function with the argument (in this case e).

My problem is on the line in the debounce function that says callback("original-args"). I would like to replace "original-args" with the actual argument that was passed into the callback. How do I get access to that argument?

  button.addEventListener("click", debounce(e => {
    let elem = document.createElement("P"); 
    elem.textContent = "Clicked";
    container.appendChild(elem);
  }, 2000))

  function debounce(callback, delay) {
    return function() {
      setTimeout(() => {
        callback("original-args")
      }, delay)
    }
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do something like the following:

button.addEventListener(
  "click",
  debounce(
    (e) => {
      let elem = document.createElement("P");
      elem.textContent = "Clicked";
      container.appendChild(elem);
    },
    2000
  )
);

function debounce(callback, delay) {
  return function (...args) {
    setTimeout(() => {
      callback(...args);
    }, delay);
  };
}

So you can pass the ...args down to your debounced function. The ...args is a spread operator that means take any number of arguments and store them inside the variable args.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!