Sobes.tech
Middle

How do you interact with the event loop?

sobes.tech AI

Answer from AI

I do not interact directly with the event loop; it is an internal mechanism of the JavaScript engine (for example, V8 in Node.js and browsers). My interaction occurs indirectly through asynchronous operations.

Main points of contact:

  • Timers: setTimeout, setInterval. They place tasks in the callback queue, which will be executed by the event loop after the specified time.
  • Promises: Promise. Their methods (then, catch, finally) register callbacks that are executed asynchronously in the microtask queue of the event loop.
  • Asynchronous input-output operations: Requests to the server (fetch, XMLHttpRequest), working with the file system in Node.js. Their completion triggers the placement of corresponding callbacks in the macro task or microtask queue.
  • DOM event handlers: addEventListener. Callbacks of handlers are executed when the event loop processes an event that occurred in the DOM.

Example of using promises for an asynchronous operation:

// Asynchronous function
async function fetchData(url) {
  try {
    const response = await fetch(url); // Asynchronous operation
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    const data = await response.json(); // Asynchronous operation
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error; // Rethrow the error
  }
}

// Calling the asynchronous function and handling the result
fetchData('https://api.example.com/data')
  .then(data => {
    console.log('Received data:', data); // This callback will execute asynchronously
  })
  .catch(error => {
    console.error('An error occurred:', error); // This callback will execute on error
  });

console.log('This code runs BEFORE the asynchronous operations complete.'); // Synchronous code

Understanding how the event loop works helps me write non-blocking code, manage asynchronous operations efficiently, and avoid interface freezing. I am aware that long synchronous operations block the main thread and the event loop, so I try to avoid them or move them to web workers.