With this idea in our heads now, let's take a look at some theories that go hand and hand with event loops
This is responsible for keeping the track of all operations that need to be performed. Whenever the particular snippet of code is ran, it gets popped from the stack. This stack is continuously checked to see if another line of code needs to be executed. Once this is empty, the event loop will look towards the event queue to see if there are code executions waiting to be done.
The Event Queue
The Event Queue has the role of holding code executions that are waiting to be ran. This uses the data structure call queue. The queue structure allows the future code to executed in the correct order. Think of this as the waiting room for any and all code that is below the current line being executed
SetTimeout is used to have a function run after a certain amount of time at that interval (measured in MS). When this is processed in the call stack, the function is sent off to the server (or API) that will wait until the defined interval is met. After the interval, the API will send it back into the queue for processing.
By doing this setTimeout, when it is added to the queue, we create a system that is running async operations. The browser API is acting as individual threads.
This function is very similar to setTimeout(); however, setInterval() keeps triggering the function after every given interval, while setTimeout() will only trigger once.
setInterval() should be used if you want to have a continuous call of a certain expression or function. If you do not use setInterval(), you will need to need to call your setTimeout() at the end of every code block that you want to run.
Understanding how the event loop looks at code information will allow you to really set up your functions in the proper order. With this knowledge, you will be able to write functional code that isn't run out of order. Finally, the event loop allows us to make use of multiple single threaded processes creating a faster response time overall.
To close up, looking at event loops may seem scary as a whole. However, once event loops are broken down, they begin to make a clearer picture. Hopefully, this short blog helped you to better understand event loops.
Top comments (0)