How browser executes Javascript and renders asynchronously

Javascript execution is single-threaded. It uses a task queue and the stack to execute stuff.

This piece of code:

for (var i=0;i<length;i++) {
     setTimeout(drawChartFunc,0);
}

Will add [length] setTimeouts calls on the task queue and excute all of them subsequently (0 ms timeout). Only the last operation will update the the screen, because all of the timeout tasks come first on the stack (after the loop, the task queue contains [length] setTimeout calls). Every timeout executes drawChartFunc. Now drawChartFunc does put a screen update function on the task queue, but the remaining timeouts come first, so first the next timeout is executed – the screen update functions can only be executed after the [length] setTimeout calls are finished (taken of the task queue/stack). This is also done subsequently, but very fast. If your eyes where trained to see nanosecond transitions, you may have spotted the subsequent numbers in the output 😉

Now

function updateLater() {
     drawChartFunc();
     i++;
     if (i < length) { 
         setTimeout(updateLater, 0);
     }
 }

Will first run drawChartFunc putting the screen update on the task queue, then put increment i on the task queue and – if applicable – after that add a new setTimeout to the task queue. In other words, drawChartFunc is put on the stack, that puts the screen update on the stack, both are executed, an subsequently the timeout is put on the stack, putting drawChartFunc on the stack … etc.

Concering the javascript task queue/stack: this video was really useful to me.

Here’s your jsFiddle, rewritten a bit. It shows you the queuing process for both methods.

Leave a Comment