简体   繁体   中英

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)
    }
  }

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 .

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