Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

456
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda