How do I adjust the sequence of JavaScript events within a single function?
<p>Is there a way I can tell the browser to wait to start on function until after another is completed?  </p>

<p>For example, in the following for loop, I'd like for contact() to fire and conclude, prior to moveForward() commencing.</p>

<pre><code>for ($i = 0; $i &lt;= ($slugPace - 1); $i++ ) {
    contract();
    moveForward();
    reset();
};
</code></pre>

<p>I attempted using <code>$.when(// your first function).then(// your second function);</code> mentioned in <a href="http://stackoverflow.com/questions/6563508/how-can-i-execute-the-events-in-sequence-in-jquery-ajax-function">this stackoverflow thread</a>, but the JS functions in the three listed functions continued to fire simultaneously.</p>

<p>Here is the code in total, if that helps:</p>

<pre><code>    //Contracting the slug once:
    function contract(){
        $("#slug").animate({
            marginTop: 0,
            width: $slugThinner,
            height: $slugHigher,
        }, 250);
        $(".slugContainer").animate({
            marginLeft: $slugLeftMargin,
        }, 250);
    };

    //Extending the slug out and move him forward once:
    function moveForward(){
        $slugLeftMargin += $slugStepsLength;
        $("#slug").animate({
            marginTop: $slugMarginJS,
            width: $slugWide,
            height: $slugHigh,
        }, 250);
        $(".slugContainer").animate({
            marginLeft: $slugLeftMargin,
        }, 250);
    };

    function movement(){
        for ($i = 0; $i &lt;= $slugStepsTotal; $i++ ) {
            contract();
            moveForward();
        };
    }

    function reset(){
        if ($slugLeftMargin &gt; $screenWidth) {
            $slugLeftMargin = $slugWide * -1;
            $("#slug").stop().hide;
            $(".slugContainer").stop.css('margin-left',$slugLeftMargin);
            for ($i = 0; $i &lt;= ($slugPace - 1); $i++ ) {
                contract();
                moveForward();
            };
        }
    }

    //Looping the contractions to move our little friend across the screen:
    $("#slug").click(function(){
        //alert('Slug width: ' + $slugWide + ', Slug height: ' + $slugHigh + ', Screen width: ' + $screenWidth + ', Slug steps total: ' + $slugStepsTotal + ', Slug higher: ' + $slugHigher + ', Slug thinner: ' + $slugThinner);
        //alert($slugStepsTotal);
        //alert('One step: ' + $slugStepsLength + '; Total steps: ' + $slugStepsTotal + '; Screen width: ' + $screenWidth);
        $("#slug").show();
        $(".clickMe").fadeOut(300);
        $.when(movement).then(reset());
    });
</code></pre>

<p>Thank you in advance for your help.</p>
