title: How to force javascript function execute synchronously/sequentially?
body: <p>I am creating a utility method which helps fading the elements sequentially with jQuery. As you can see in the below code I am adding an extra class as <code>alreadyFadedIn</code> a flag. At the end of the method call <code>sequentiallyFadeIn(...)</code> I would like to perform the <code>cleanUp</code> where I want to remove the flag class which I added in the selected elements inside the <code>sequentiallyFadeIn(...)</code> method.</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
  $(document).ready(function() {
  
      function sequentialFadeIn(selectorText, speed, display, callBack) {
  
          display = typeof display !== 'undefined' ? display : "block";
  
          function helper() {
              nextElementToFadeIn = $(selectorText).not(".alreadyFadedIn").first();
              nextElementToFadeIn.fadeIn(speed, function() {
                  $(this).addClass("alreadyFadedIn");
                  helper();
              }).css("display", display);
          }
          helper();
  
          callBack(selectorText);      
      }
      sequentialFadeIn(".toBeFaddedIn", "slow", "inline-block",function cleanUp(selectorText1){
              $(selectorText1).removeClass("alreadyFadedIn");
              console.log("Clean up has been performed.");
                      console.log("Selector Text: " +selectorText1);
  
          } );
  
  });
  
  &lt;/script&gt;
  
  &lt;/head&gt;
  &lt;body&gt;&lt;style media="screen" type="text/css"&gt;
  .hello {
      background-color: blue;
      height:50px;
      width: 50px;
      display: none;
  
  }
  &lt;/style&gt;
  
  &lt;div class="hello toBeFaddedIn"&gt;&lt;/div&gt;
  &lt;div class="hello toBeFaddedIn"&gt;&lt;/div&gt;
  &lt;div class="hello toBeFaddedIn"&gt;&lt;/div&gt;
  &lt;div class="hello toBeFaddedIn"&gt;&lt;/div&gt;
  &lt;div class="hello toBeFaddedIn"&gt;&lt;/div&gt;
  
  &lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>While looking at the inspect element I notice that class <code>alreadyFadedIn</code> is not getting removed. The cause seems to me is the cleanUp method gets executed asynchronously along with main logic of the <code>sequentiallyFadeIn</code> method which is in <code>helper()</code>. You can also notice the log message "Clean up has been performed." getting printed even before the divs have completed fading in.  </p>
  
  <p>How can I make the <code>cleanUp</code> call getting executed after the completion of main logic in the <code>sequentiallyFadedIn</code> method? Any suggestions?</p>
  
  <p>Code on jsfiddle: <a href="http://jsfiddle.net/BztLx/11/" rel="nofollow">http://jsfiddle.net/BztLx/11/</a></p>