Handling setTimeout correctly in JavaScript
<p>I am trying to animate some elements on a page using JavaScript (CSS animations with sprites will not work for what I need to do).</p>

<p>I am currently doing something like this;</p>

<pre><code>function animate_element(current_id)
{
    var next_id = parseInt(current_id, 10) + 1;
    $('#lighthouse')[0].src = '/element_' + next_id + '.png';

    if (next_id &gt;= 8) {
        next_id = 0;
    }     

    setTimeout(function() {
        animate_element(next_id);
    }, 750);
}
</code></pre>

<p>Technically this works, but this is going to be one of many animations on the page that will be doing something similar and I am worried this is an inefficient way of doing it.</p>

<p>I know best practice is to use <code>clearTimeout()</code> before calling setTimeout, but I don't know how to record the setTimeout and recursively pass it into itself (if that makes any sense!).</p>

<p>Any guidance on the best practice way of doing this would be much appreciated.</p>
