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).
I am currently doing something like this;
function animate_element(current_id)
{
var next_id = parseInt(current_id, 10) + 1;
$('#lighthouse')[0].src = '/element_' + next_id + '.png';
if (next_id >= 8) {
next_id = 0;
}
setTimeout(function() {
animate_element(next_id);
}, 750);
}
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.
I know best practice is to use clearTimeout() before calling setTimeout, but I don't know how to record the setTimeout and recursively pass it into itself (if that makes any sense!).
Any guidance on the best practice way of doing this would be much appreciated.
setTimeoutis plenty "efficient", in that it doesn't waste any CPU cycles or tie up anything else. I'd say your fine.