Javascript is asynchronous – let’s talk about how the event loop works. Everything in Javascript is asynchronous, but what does that mean?
Javascript is a single thread language that can only run 1 process at a time. It works from the top of the Javascript file to the bottom, one function/variable at a time. But what if you need things to operate in a manner that isn’t from top to bottom?
Example Time
Let’s look at an example of a callback in an event loop:
console.log('Starting'); setTimeout(function(){ console.log('Running'); }, 2000); console.log('ending');
In the code above, you will see setTimeout
, which is an example of a callback so it can run a callback function (in this case console.log('Running');
) after a specified timeout (in this case 2000 ms or 2 seconds) and then run the next line of code until the time in that timeout has elapsed – then it will return and run the callback.
A Better Explanation
Check out this super amazing video to explain more about the event loop and how call backs work by Philip Roberts.
He created a little tool called loupe you can use to visualize the call stack, web APIs, and the Callback Queue. I’m going to use it to demonstrate what happens in that callback loop.
A Short Summary
What you will see happen is “console.log("starting");
” will go into the callstack, then an anonymous function is called in the callstack, but it sees there is a set timeout. It continues trucking along to the next line of code but drops the anonymous function into the Web APIs — which uses the browser’s memory. From there it awaits the 2 second delay, then adds it to the callback queue. The callback queue awaits the currently running line of code which will be the console.log("ending");
and then executes the anonymous function of console.log("running");
. There you have it, a very basic callback loop demonstrated. Seriously though, if you haven’t watched the video above, this little demonstration won’t do it justice. Give it a watch!
My Ask & Final Thoughts
Callbacks can be really confusing, being able to visualize what happens in the browser at runtime is especially helpful to get a better understanding of what goes on when you leverage these amazing callback/event loop tools to create more functionality in your application.
If you found this article helpful, share/retweet it and follow me on twitter @codingwithdrewk!
Leave a Reply