An Event Loop in JavaScript is a mechanism that allows for the execution of multiple tasks or events in an asynchronous manner. It ensures that the program remains responsive by continuously checking for any pending tasks or events in a loop.
The event loop works by maintaining a queue of tasks or events, known as the “event queue”. When an asynchronous task or event occurs, it is added to the event queue. The event loop continuously checks if there are any tasks in the event queue, and if so, it picks the next task and executes it.
Here is a concise and structured answer in HTML format:
<!DOCTYPE html> <html> <head> <title>Event Loop in JavaScript</title> </head> <body> <h1>Event Loop in JavaScript</h1> <script> // Example code demonstrating the event loop console.log("Start"); // Asynchronous task using setTimeout setTimeout(function() { console.log("Async Task 1"); }, 2000); // Synchronous task console.log("Sync Task"); // Asynchronous task using Promise new Promise(function(resolve, reject) { setTimeout(function() { resolve("Async Task 2"); }, 1000); }).then(function(result) { console.log(result); }); console.log("End"); </script> </body> </html>
In the above example, we have two asynchronous tasks: one using setTimeout and another using a Promise. The event loop ensures that these tasks are executed asynchronously while the synchronous task is executed immediately. The output in the console will be:
Start Sync Task End Async Task 2 Async Task 1
This demonstrates how the event loop allows for the execution of multiple tasks in an asynchronous manner, ensuring that the program remains responsive.