Fire function after each() has completed
<p>this is slightly related to this question
<a href="http://stackoverflow.com/questions/2358205/invoking-a-jquery-function-after-each-has-completed">Invoking a jQuery function after .each() has completed</a></p>

<p>But the solution doesn't quite seem to work for me.</p>

<p>Basically I have piece of JavaScript that calculates the width of some elements:</p>

<pre><code>var totalWidth = 0;
$element.find('li').each(function () {
    totalWidth += $(this).width();
});
</code></pre>

<p>After this I want to then use the width to set another element:</p>

<pre><code>$element.width(totalWidth);
</code></pre>

<p>If I attach the debugger it works but if I just run it it doesn't. Which makes me think that the width is being set before the <code>.each()</code> completes.</p>

<p>I tried using <code>.promise()</code> to fix this issue but it doesn't appear to make a difference. </p>

<pre><code>var totalWidth = 0;
$element.find('li').each(function () {
    totalWidth += $(this).width();
});

$element.promise().done(function () {
    $element.width(totalWidth);
});
</code></pre>

<p>Here's my HTML</p>

<pre><code>&lt;div class="carousel"&gt;
        &lt;ul&gt;
            &lt;li&gt;
                &lt;img src="/Images/Travel2New/Adverts/advertHolder_1.png" /&gt;
            &lt;/li&gt;
            &lt;li&gt;
                &lt;img src="/Images/Travel2New/Adverts/advertHolder_2.png" /&gt;
            &lt;/li&gt;
            &lt;li&gt;
                &lt;img src="/Images/Travel2New/Adverts/advertHolder_3.png" /&gt;
            &lt;/li&gt;
            &lt;li&gt;
                &lt;img src="/Images/Travel2New/Adverts/advertHolder_4.png" /&gt;
            &lt;/li&gt;
            &lt;li&gt;
                &lt;img src="/Images/Travel2New/Adverts/advertHolder_5.png" /&gt;
            &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/div&gt;
</code></pre>

<p>Any ideas?</p>
