The event loop in JavaScript is responsible for handling asynchronous operations in a non-blocking way. It allows the execution of code to continue while waiting for I/O operations, such as network requests or file system access.
Here's a simple example of how the event loop works:
index.tsx147 chars8 lines
Output:
index.tsx29 chars5 lines
In this example, console.log('start')
is executed first, followed by console.log('end')
. The setTimeout
function is scheduled to run after 0 milliseconds and Promise.resolve().then(...)
is added to the micro task queue. Since setTimeout
is added to the task queue and Promise
is added to the micro task queue, Promise
is executed before setTimeout
.
The event loop checks the task queue first and executes any tasks in the order they were added. After each task, the micro task queue is checked and any micro tasks are executed in the order they were added. This process repeats until both the task queue and micro task queue are empty.
Callbacks are a common pattern used with the event loop. For example, with an HTTP request, a callback is provided that will be executed once the response is received.
index.tsx355 chars17 lines
In this example, the getData
function takes a URL and a callback. When the request is loaded, the callback is executed with the response data. This approach allows the rest of the code to continue running while the request is being made.
gistlibby LogSnag