event loop in javascript

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.tsx
console.log('start');

setTimeout(() => console.log('setTimeout'), 0);

Promise.resolve().then(() => console.log('Promise'));

console.log('end');
147 chars
8 lines

Output:

index.tsx
start
end
Promise
setTimeout
29 chars
5 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.tsx
function getData(url, callback) {
  const request = new XMLHttpRequest();
  request.open('GET', url);

  request.onload = () => {
    if (request.status === 200) {
      callback(request.response);
    } else {
      callback('Error');
    }
  };

  request.send();
}

getData('https://jsonplaceholder.typicode.com/todos/1', (data) => console.log(data));
355 chars
17 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