Search code examples
javascriptfunctionaddeventlistener

Adding Cooldown to Event Listener with JavaScript


In a JavaScript function, I have this code:

clicker1.addEventListener("click", nextImage, true);

The problem is that when the button with this event is clicked rapidly, it causes errors.

I need to make it so once the button is clicked there, is a delay where the click event doesn't run the function.


Solution

  • How about disabling the button for a short while using setTimeout. In this example, the button is disabled for 2000 ms.

    function myFunction() {
      console.log('clicked !!');
      document.getElementById("myButton").disabled = true;
      setTimeout(function(){
        document.getElementById("myButton").disabled = false;
      },2000);
    }
    <button onClick="myFunction()" id="myButton">Press me</button>