DEV Community

Cover image for What is an event loop in JavaScript?
Hamza Nadeem
Hamza Nadeem

Posted on

What is an event loop in JavaScript?

The event loop is the core concept of JavaScript but for the people who just started writing code in JavaScript, they found it a bit confusing.

So, what really an event loop is?

The event loop is responsible for asynchronous programming in JavaScript. JavaScript is a single thread language but using some great data structures techniques, it gives us the ability of multi-threading. Let's take a look at how things work.

JavaScript uses call stack to keep track of executions line by line. All the operations are pushed to the stack in order and whenever an operation is completed it is popped out of the stack.

The event queue is responsible for sending new functions to the track for processing. It uses the queue data structure to maintain the correct sequence in which all operations should be sent for execution.

Let's take an example of the setTimeout method. When a setTimeout operation is processed in the call stack, it is sent to the related Browser API which waits till the specified time to send this operation back in for processing to the event queue.

The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed.

Top comments (0)