I have a javascript animation code –
function animate(position)
{
....
....
if(position++ < xyz){
animate(position); // ****this is the line that I replace with in the next attempt.
}
}
This takes around 1 seconds to execute . But if I put a timeout function with a 0 time , it takes around 15 seconds to complete .
setTimeout(function(){
animate(position);
}, 0);
Why does this huge time difference happen ? In the code I am trying to draw some pixels on an HTML5 canvas. I have omitted those codes to make my question clearer.
The reasoning for this is in the way JavaScript handles timers internally. Since JavaScript is single threaded, nothing ever runs concurrently. Passing 0 milliseconds to
setTimeoutwill just force the function to run at the first available moment. John Resig has a nice write up on this at http://ejohn.org/blog/how-javascript-timers-work/.You can see this by running the following:
twois logged beforeone.I’m assuming you have a bunch of other things running and by queuing up
animateyou are making the execution wait until those other things complete.