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.
For what you’re doing, there’s no reason to call
clearTimeout()since the next call will never happen until the last one has been executed.At that point, there’s nothing to clear.
FWIW, your code can be shortened a bit:
Or if there are several that are the same, just with a different ID, you can make it reusable like this: