2

I have a button which makes an image spin for 3s. I want the button to be disabled during the spinning. But this is not working. Below are the js functions and the css class which creates the spin.

   <script>
    function spin() {
      document.getElementById("spin_switch").disabled = true;
      document.getElementById("image-map").classList.toggle("spin");
      setTimeout(stop_spin, 3000);
      document.getElementById("spin_switch").disabled = false;
    }
    function stop_spin() {
      document.getElementById("image-map").classList.toggle("spin");
    }
   </script>
    
   <style>
    .spin {
      transform: rotate(360deg);
      webkit-transform: rotate(360deg);
      overflow: hidden;
      transition-duration: 3s;
      transition-property: transform;
    }
   </style>
Dunc
  • 33
  • 5
  • Does this answer your question? [Does Javascript setTimeout stop other script execution](https://stackoverflow.com/questions/10258012/does-javascript-settimeout-stop-other-script-execution) – Heretic Monkey Jan 09 '21 at 23:49

1 Answers1

1

You have to move this line

document.getElementById("spin_switch").disabled = false;

into the stop_spin function:

function spin() {
   document.getElementById("spin_switch").disabled = true;
   document.getElementById("image-map").classList.toggle("spin");
   setTimeout(stop_spin, 3000);
}
function stop_spin() {
   document.getElementById("image-map").classList.toggle("spin");
   document.getElementById("spin_switch").disabled = false;
}

Otherwise the spin_switch will be enabled again immediately. setTimeout does not stop the entire script. It just registers a callback to be executed after the given timeout has expired.

Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44
  • Thanks. i thought the document.getElementById("spin_switch").disabled = false line wouldnt run until after the 3s setTimeout function finished. – Dunc Jan 09 '21 at 23:45