top of page
Logo der Online Agentur mdwp

Event Loop

The term 'Event Loop' isn't exclusive to React JS. It's a fundamental concept of JavaScript, which is essential in understanding how asynchronous operations work in JavaScript or in extensions of JavaScript like React JS.

The "Event Loop" is a process model that JavaScript uses for processing tasks, executing codes, managing events, and rendering updates on the browser. The event loop's primary role is to monitor the call stack and the callback queue. If the call stack is empty, it invokes the first event in the queue and pushes it onto the call stack, which effectively runs the event/callback.

Here’s a basic example of how JavaScript (and thus React JS) works with the Event loop:

console.log('Hi'); //First Task

setTimeout(function cb() {
console.log('There'); //Callback placed in queue and invoked when the stack is empty.
}, 5000);

console.log('Hello'); //Second Task
When the JavaScript engine runs the code:
- It first prints 'Hi' to the console.
- It then comes across the `setTimeout` function and sets up a timer. Once the timer expires, the engine places the callback function `cb` in the "Callback Queue". Meanwhile, the engine doesn't wait for the timer to finish and moves on to the next line of code.
- It then prints 'Hello' to the console.
- After the messages get printed and the call stack is empty, the `setTimeout` finishes timing, the callback `cb` is placed on the call stack, and 'There' is printed to the console.

So, the Event Loop enables JavaScript to perform non-blocking activities, even though JavaScript itself is blocking (synchronous). This is especially important in frontend libraries like React JS, which need to handle user interactions, API calls and UI updates in real time.

bottom of page