Question

How can I implement in js that whenever I press a button that the function gets executed once and then waits a couple of seconds so the user has to wait. I would like to implement this because if I spam the button the actions get executed too fast. The setInterval etc is not what I want because it simply waits a couple of seconds but thereafter you will get bombed with alert message's for instance. So an interval on a function but thereafter it needs to be executed once.

I hope that I have explained this clearly,

Thanks in advance.

Was it helpful?

Solution

Use setTimeout instead of setInterval - that will fire the function to run only once

Or even better - in the event listener save the last clicked time in the global variable. something like:

var last_clicked = 0;
button.onclick = function(){
  if (Date.now() - last_clicked < 10000) return;
  last_clicked = Date.now();
  // Here You should put the listener code
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top