title: Javascript wait for one animation to finish before the next one begins
body: <p>I have a Javascript function (Not jQuery) that animates a box opening or closing. The problem is that I close the box, run some code that changes the content, and then reopen it.</p>
  
  <p>Now the "problem" is that the rest of the code is too fast, and so it never even manages to close, let alone reopen. I could make the animation not be allowed to run again internally unless the last one was finished, but this would limit it if I say, were to want to run it twice on two different objects. </p>
  
  <p>So what's the best method to prevent this? My thought was possibly a timeout that says to wait before running the animation, but that seems hacky, an I wasn't sure if there was a better solution?</p>
  
  <p>Thanks.</p>
  
  <pre><code>function animate(boxID, step, limit, speed){
      // Add timeout property to animate function/object if it doesn't exist already
      if(animate.timeout == undefined) animate.timeout = 0;
  
      // Clear the current timeout
      clearTimeout(animate.timeout);
  
      // Initialize box and current box height
      var box = document.getElementById(boxID);
      var h   = box.clientHeight;
  
      // Check if we want the step needs to be changed to pos/neg based on which direction is wanted to be going
      if(h &lt; limit &amp;&amp; step &lt; 0 || // Positive
         h &gt; limit &amp;&amp; step &gt; 0){  // Negative
          step *= -1;
      }
  
  
      // If the step is positive, then we need to be below the limit, or if negative, then greater than the limit
      if((step &gt; 0 &amp;&amp; h &lt;= limit - step) || (step &lt; 0 &amp;&amp; h &gt;= limit - step)){
          // Set new height
          box.style.height = h + step + "px";
  
          // Start new timeout
          animate.timeout = setTimeout(function(){ animate(boxID, step, limit, speed, 1); }, speed);
      }
      else{
          box.style.height = limit + "px"; // Set to the exact height
      }
  }
  </code></pre>