Running the code

When I was learning computer programming, before the internet, we learned that there were a couple of main ways to run the computer code: first in, first out, where the first instruction to the computer is the first one completed, and last in, first out, where the latest instruction to the computer is the one that is run first.

Now computer code is run with browsers (e.g. Chrome, Firefox), which makes things a little more complicated. The set of instructions are still put on a virtual “stack,” and in JavaScript, instructions are run one at a time. This is fine if the instructions are simple ones, such as console.log (which simply prints to the console). However, if the instructions are complicated and take a long time to run, this can hold up the rest of the code. Meanwhile, the browser is waiting for JavaScript instructions to complete so it can refresh the screen (at a preferred rate of 60 frames per second).

There’s a way to make things run faster. The browser has its own stack/storage for instructions called webapi, and there’s a secondary storage area called the task/callback queue. A programmer can help out by placing a function (or subroutine) within an instruction called setTimeout, which says wait a certain number of milliseconds (at minimum, it can take longer) before running this instruction. In addition, if a programmer knows that something will take a while, the code can be placed within a setTimeout of zero, which means essentially to hold the code until the stack is clear (and then run it).

The structure, then, is this: there’s a stack running the code (instructions). There’s a browser stack called webapi which holds code that is to be run later. There is another intermediate holding area called the task/callback queue. The stack is taking code and running it. The webapi holds code for a certain amount of time, and then places that code into the callback queue. A mechanism called the event loop checks the stack, and if the stack is empty, it places the item in the callback queue into the stack so that it can be run. (Items can also be placed in the callback queue directly for holding until the stack is empty.)

Essentially, we have webapi – – > callback queue – – > event loop – – >stack.

The goal of the programmer is not to “block the event loop” with code that takes a (relatively) long time to run, but to allow the faster instructions to go into the stack, and the more complex instructions to go into the callback queue or webapi to wait and run when the stack is clear.

This produces a web page which loads and responds quickly.

Leave a Reply

Your email address will not be published. Required fields are marked *