Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
Execute function only once after multiple clicks in a row JavaScript

I have two quantity selector buttons.

After the user clicks in any of these buttons (increasing or decreasing quantity), I need to run a function.

But the user can click several times in a row, and I want to execute the function only once.

Like, wait 1 second after each click to run the function. If within this 1 second the user clicks the button again, reset the timer and wait for another second to run the function. When the user doesn´t click again within 1 second, run the function.

What´s the best way to do that in vanilla javascript?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You just need to start a 1 second timer and reset it whenever the button click happens.

let timer

function handleClick() {
  clearTimeout(timer)
  timer = setTimeout(doSomething, 1000);
}

function doSomething() {
  let div = document.getElementById("list")
  let p = document.createElement("p")
  p.textContent = "1 second passed without a click"
  div.append(p)
}
<!DOCTYPE html>
<html>

<body>
  <button onclick="handleClick()">Click me</button>
  <div id=list></div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

I see two solutions:

  1. If each click triggers some request, then disable button until the request is completed
  2. Use throttling for the function invoke. You can use RxJS's throttle or you can write your own throttle method.

https://medium.com/nerd-for-tech/debouncing-throttling-in-javascript-d36ace200cea

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try this in Vanilla JS :

const btn = document.querySelector('#btn');

const callback = event => {
 console.log(event);
 clearInterval(interval);
}

let interval;

btn.addEventListener('click', event => {
 clearInterval(interval);
 interval = setInterval( () => callback(event), 1000);
});

And the HTML :

<html>
<body>
 <button id="btn">test</button>
</body>
</html>

That way you can pass the event instance to your callback.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda