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

153
Views
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 answers
Answer question

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 Report

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 Report

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 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!