Event Loop Sort of Simplified(Along with the Other Parts of JavaScript)

Before I began just remember, my style is short and sweet. My goal is to make a one to two minute read about the subject. Also I am not JS expert for now so take this post with a grain of salt. *Deep breath* Here goes something…

Think of JavaScript as a gadget, with parts inside constantly running. JavaScript’s M.O. is to run each task or command one line at a time and the parts’ job inside of the gadget is to perform accordingly in order for JS as a whole to perform. JS consist of 5 inner parts: the console, the stack, the event loop, the task queue, and the command line. The webApi is another part but think external and apart/not apart of JS at the same time. We’ll get to that part later. How it all works starts like this…

Step 1: The command lines filled with JS code is read one line at a time and continuously read even if there’s a line that requires of JS to hold off from outputting the information until a later time. Thats the wonderful magic of JS, its asynchronous mean it will continue to run.

Step 2: Each line is brought over to the stack awaiting to be executed. Think a line at the DPS or Wal-Mart and your in that line waiting to be assessed. The way each line is processed is by the FILO method (First In Last Out) which when I think about it, kind of doesn’t make sense to the analogy I used earlier but 12am and I can barely keep my eyes opened so it’ll do for now. Back to the subject. Lets say a line had a function that was inside of a setTimeout function. That said function in the stack now goes from it current location to the webApi awaiting its return to the stack.

Step 3: The webApi is a browser based function that works with JS to hold on to output information JS has requested after a certain time has passed. This is one of many purposes of the webApis.

Step 4: Once the information is released by the webApi it is then transferred to the task queue where it awaits the call stack to be empty before the task queue releases the output function back to the call stack itself.

Step 5: How that output function is transferred from the task queue to the call stack is by the Event Loop piece. That’s simply it’s sole purpose. This whole post is based on a part with one job. Incredible.

Step 6: Once the output function is transferred to the call stack, it is re-executed, and the data is then brought to the console where it will be logged and printed for the user to see.

While that one hypothetical command line function went through the merry go round, JS continued to run it course which in real time can be a fraction of a second. Asynchronous reading at it’s best. Was that 2 mins? Who cares. You just learned about Event Loops(and the other parts.)

Like what you read? Give Leon Ikpo a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.