JavaScript Under The Hood [3} - Asynchronous JavaScript, Task Queue & Event Loop

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys welcome to part three of javascript under the hood so this is a series where we look at different concepts and what happens in the background when we run specific javascript code and how everything works under the hood hence the the name of the series so in the first video we talked about how javascript is single threaded we have the thread of execution we talked about the call stack and how that works in the second video we looked at execution context and hoisting and i would suggest that you go back and watch those two videos if you haven't already the first one i think is 10 minutes and the second one i think is 15 minutes so in this one in this video i want to get into a synchronous javascript and talk about how that's possible we know that javascript at its core is synchronous but we do have web apis along with something called the task queue and the event loop that can help us write asynchronous code so that's what we're going to talk about in this video [Music] all right so before we start to talk about asynchronous javascript i just want to go back to one of the slides i think we we talked about this in the first video it's just how javascript works at its core we have this single thread and everything on this thread happens line by line it's very simple so operation one completes operation two waits for operation one to be done then that runs and so on and then we have our call stack which manages our functions and execution context now where we run into a problem is when one of these operations takes a while so for instance if it's fetching data from a server or maybe you're a node.js and it's writing data or reading data to or from a file that could take a while and you're waiting on that to complete for the next operation that's what we call blocking code or blocking operations or just blocking and it refers to operations that block further execution until that operation completes and then non-blocking is just the opposite it refers to code that does not block execution now to make this a little bit more clear i want to show you uh kind of a real world example and and don't worry about understanding exactly what this code does and this is the code after we look at this i'm going to show you how this is possible and what happens under the hood so this is actually node.js we're using the fs module which is the file system module we can read and write to files and stuff like that and i wanted to show you this example because there's there's two methods that do the same thing but one does it asynchronously one does it synchronously so read file is a method on this fs object that reads a file in an asynchronous non-blocking way so it doesn't block your code read file sync is the synchronous version of that method and it works in a blocking way so over here read file sync what's going to happen is when we hit this line it's going to stop the rest of the execution of this code until it this completes until this operation or this this function is complete and then it will go ahead and log the data from the file and then it will do this right here just calculates up a sum okay and then the output is going to be this because it stops reads the file then it logs the data then it does the sum over here we're using read file which is an asynchronous non-blocking function and the in the way we handle this is we pass in a callback function you can see this has two parameters being passed in this one has three and the third is a callback function and basically what we're saying is that whatever we put in that function is what we want to happen as soon as this is actually done but it's not going to block and stop the rest of the code it'll just keep going and then once this is done that callback will get added to the stack all right and then this will be the output here because it keeps going it logs the sum and then once it's fin once this is finished the callback fires off and then it will show us the data from the file all right now this read file is not available to us in the browser but there's a lot of web apis that that are available to us that work in this way in an asynchronous way that takes in a call back so i'm going to show you a diagram and i know that this can be a little overwhelming and again i'm not the best diagram creator but this right here this yellow box is our javascript engine okay and this is where our call stack is in every function that we run we have our global execution context and then outside of that we have a bunch of web apis that we can use now these web apis are on the global object if you watched the last video i showed you that when we run a javascript file it creates what we call a global execution context and in the creation phase of that it creates the global object and that's always available to us if i type in here window that's our global object and if we look down here let's look for set timeout because that's one of these apis we can use so right here you can see we have set timeout and set interval so these are actually web apis in the browser a lot of people think that set timeout is actually part of javascript this is not part of the javascript spec it's an api in the browser that we can use to do things asynchronously if we want to um you know have something happen uh a few seconds later or whatever there's there's an internal timer in the browser that this uses so to set interval now in addition to those we also have the the whole dom api so you know the document object when we want to select elements and we put event listeners on them that's another api that we have available to us that it's not part of javascript when you use node.js you don't have access to the document object model api because there is no document it runs on the server fetch wasn't in node.js for a long time now it's it's getting put into it but this fetch is not part of the part of the javascript spec all right so at the moment just realize that outside of the javascript engine are these web apis that we can use so i want to give you an example using set timeout so let's actually jump into our code here and i'm just going to reload this and and let's go ahead and set timeout now this takes in a callback just like that that read file method that i showed you this takes in a callback function and you can either do it like this or if you want to shorten it up and make it an arrow function and i know a lot of you guys know already know how to do this but in here we can do whatever we want let's just say console.log and we'll say i'll just say hello from callback okay and then the second argument or second parameter that's going to get passed in is going to be the amount of milliseconds that i want to wait until that callback fires off so we'll say 2000 milliseconds which is two seconds and then directly under it let's do a console log and we'll just say run me so i'm going to save this and let's see what happens if i run this we see run me and then two seconds later we see hello from callback so this didn't work in that traditional you know synchronous one thing happens after another we use set timeout to be able to kind of go off to the side and register a callback and then keep going keep running the script it didn't have to pause for two seconds and then do the run me so i'm going to use this diagram to kind of show you what just happened under the hood now in this diagram i have set timeout being called from a function we didn't we just called it from the global scope but let's say it was called from a function it really doesn't matter and then here what happens is in the web api it registers a callback function the callback we passed in which said hello from callback and then what happens is that gets put into a what's called a task queue or sometimes called a callback queue now a queue is just a data structure it's it's it's a programming data structure just like a stack but it works a little differently call stacks like we talked about in the first video are last in first out that means the last thing that's put on top of the stack is the first thing that's put out with a queue it's first in first out okay so the first thing that's put in which in this case would be this callback is then put as in out goes out and then this one comes in goes out this side so it's just basically first in first out simple now that callback or any callbacks that are in this queue have to be put on the stack to be executed and this is where the event loop comes in this is a loop that will continuously run to check to see if there's anything in the task queue and if there is once the call stack execution is complete and the stack is cleared the event loop will basically pick up that task from the queue and put it on the stack to be executed that's the event loop sole purpose now each task in the queue is executed at the moment a new iteration of the loop begins okay so it goes through iterations or what are also called ticks and tasks added to the queue after the iteration begins won't run until the next iteration or the next tick so you can almost think of it as like one of those revolving doors at the mall or something and once people get in or once call backs or tasks get in and it starts moving nobody else can get in until it comes back around until the next iteration or next tick all right so hopefully you can kind of visualize that in your head a little bit in the example that i showed you we used to set timeout but it works like this for a lot of different things in in that read file example that node.js example i showed you pretty much does the same thing because it uses the v8 engine it has an event loop it has a task queue um so i mean if we look at like the dom api methods let's just jump into the code real quick here so if i were to do something like document dot get element by id and we got something i don't know we'll call it test and then maybe we add an event listener onto it so when we add an event listener we pass in the the type of event we're listening for listening for which in this case we'll say a click and then we put in a function here okay so this function will also get put in the in the task queue or the callback queue all right now when it comes to promises it works a little bit different so i'm going to show you another diagram to make this a little more complicated so when we use let's say the fetch api we're dealing with promises and with promises instead of using the task queue that we just talked about we use something called promise jobs or the v8 engine calls it the micro task queue so if we fetch some data we get a promise back and then we have a callback that goes into the micro task queue now the microtask queue does have a higher priority than the task queue or the callback queue if you want to call it that and it doesn't have to wait until the iteration ends with the event loop there's also something called browser observers and those are also handled uh in the micro task queue as well now i don't want to get too deep into this into like micro tasks versus tasks there's a great medium article that i'm going to put in the description and he goes really deep into this but you don't really need to need to get that deep as a javascript developer i would say the main thing you need to understand is basically what you see right here you need to understand that javascript is synchronous everything happens each operation happens uh synchronously but then you also have the help of asynchronous web apis where you can utilize callbacks and promises to send callbacks or tasks i should say to the queue and then those get put on the stack and they're executed just like any other function so that's kind of the bottom line of what i want you guys to understand from this video but that's it guys the next video is either going to be on how javascript is interpreted within the javascript engine or on memory i haven't decided which one i want to do next but either way i'll see you in the next video
Info
Channel: Traversy Media
Views: 33,175
Rating: undefined out of 5
Keywords: javascript, event loop, asynchronous javascript, javascript async, javascript task queue, js
Id: 28AXSTCpsyU
Channel Id: undefined
Length: 12min 50sec (770 seconds)
Published: Thu Jul 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.