Reputation: 8792
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.
Upvotes: 1
Views: 151
Reputation: 12704
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 setTimeout
will 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:
setTimeout(function() {
console.log('one');
}, 0);
console.log('two');
two
is logged before one
.
I'm assuming you have a bunch of other things running and by queuing up animate
you are making the execution wait until those other things complete.
Upvotes: 3
Reputation: 1739
https://developer.mozilla.org/en/DOM/window.setTimeout has some information on setTimeout
clamping. See the "minimum delay" section.
Upvotes: 1