setTimeout in a loop and pass variables to use later
<p>Consider the following code:</p>

<pre><code>function func() {
    var totalWidths = 0;
    for( var i = 0, count = arr.length; i &lt; count; i++ ) {
        var image = arr[i];

        insertElemInDOM(image);

        preloadImage(image,function(){
            var w = image.width();
            totalWidths += w;
        });

    }
    // do something with the variable "totalWidths"
    doSomething(totalWidths)
}
</code></pre>

<p>I have 2 problems here. The image will be always the same (first problem), which one can solve with an anonymous function:</p>

<pre><code>    for(...) {
        (function(image) {
            preload(image,function() {
                // now image is the correct one
            });
        })(image);
    }
</code></pre>

<p>But how do I manage the totalWidths variable in order to use it later on doSomething(totalWidths)? The previous code would have a value of 0 for totalWidths.
Thanks!</p>
