There is an element (button) that is clicked many times, but the function must be called once. Tried through setTimeout, did not work (Probably bad tried).

  • And what guarantees, what exactly this click last and after it will not click any more? You can clean the listener, even after the first click, you can also set the state in the script, indicating whether the button was pressed at least once. - DanielOlivo
  • 2
    If I understand correctly, then you need something called debounce . You can look at the implementation in the underscope or lodash. - Arnial
  • Set the timeout, if during this time you clicked again on the button - reset the timer, if you don’t click the timer it will reach the end and your function will be called. - Moonvvell
  • one
    I tried using setTimeout, it didn’t work out, I’m trying to show exactly how I tried it and why I decided it didn't work out - Grundy

1 answer 1

I think you meant something like this:

 var timeout = 3000; var lastCall = null; function action() { if((Date.now() - lastCall) >= timeout) { alert('Action!'); } } function actionWait() { lastCall = new Date(); setTimeout(action, timeout) } 
 <button onclick="actionWait()">button</button> 

Timeout is set by timeout variable