JavaScript and TypeScript course Β· Module 4: Asynchronous JavaScript
Event Loop (Event Model)
In this lesson8
Welcome back to Jurassic Park! So far we have focused on the basics of object-oriented programming - building classes, inheritance, and composition. However, in real applications like a dinosaur park management system, we often have to deal with operations that take a lot of time - from fetching data from sensors in enclosures, communicating with security systems, to handling park visitor interactions.
In this module we will move on to a key aspect of JavaScript: its asynchronous nature and the event model it is built on. Understanding this mechanism is essential for building responsive and efficient applications that can handle many operations simultaneously - which is critical for the safety of a park full of predators!
JavaScript - A Single-Threaded Language with Asynchronous Capabilities
JavaScript is a single-threaded language. This means it can execute only one operation at a time. It is similar to having only one employee to handle all tasks in the park.
Imagine that this employee (the JavaScript thread) must:
- Check the status of the fences
- Monitor dinosaur vital signs
- Respond to messages from guests
- Control emergency systems
If they performed these tasks synchronously (one after another), they would have to fully complete one task before moving on to the next. That would be inefficient and potentially dangerous!
Fortunately, JavaScript has a clever system called the "event loop" that allows it to handle asynchronous operations despite being single-threaded.
Event Loop - The Heart of Asynchronous JavaScript
To understand the event loop, let's imagine the Jurassic Park control center. In this center we have:
- Call Stack - a list of currently executing tasks (the main tasks of our employee)
- Callback Queue - a list of tasks waiting to be executed after asynchronous operations complete
- Web APIs (in browsers) or C++ APIs (in Node.js) - external systems that can perform tasks "in the background"
- Event Loop - a mechanism that continuously checks whether the call stack is empty, and if so, moves tasks from the queue to the stack
Let's see how this works with a Jurassic Park example:
console.log("1. Starting the morning park walkthrough.");
setTimeout(() => {
console.log("4. Received data from dinosaur enclosure sensors.");
}, 2000);
fetch('https://jurassic-park-api.com/security-status')
.then(response => response.json())
.then(data => {
console.log("5. Security system status:", data.status);
});
console.log("2. Checking today's staff roster.");
console.log("3. Morning walkthrough complete.");If we run this code, we will see in the console:
1. Starting the morning park walkthrough.
2. Checking today's staff roster.
3. Morning walkthrough complete.
4. Received data from dinosaur enclosure sensors.
5. Security system status: activeWhat happened? Let's analyze it step by step:
console.log("1. Starting the morning park walkthrough.")is added to the call stack, executed, and removed from the stack.setTimeout(...)is added to the call stack. JavaScript recognizes this is an asynchronous call and passes it to the Web API, which starts the timer.setTimeoutis removed from the stack.fetch(...)is added to the call stack. JavaScript recognizes this is an asynchronous call and passes it to the Web API, which sends the HTTP request.fetchis removed from the stack.console.log("2. Checking today's staff roster.")is added to the stack, executed, and removed.console.log("3. Morning walkthrough complete.")is added to the stack, executed, and removed.The call stack is now empty, but we have two asynchronous operations in progress:
- The timer from
setTimeout - The HTTP request from
fetch
- The timer from
After 2 seconds the timer expires and the
setTimeoutcallback is added to the task queue.The event loop sees the call stack is empty, so it moves the callback from the queue to the stack.
console.log("4. Received data from dinosaur enclosure sensors.")is executed and removed from the stack.Meanwhile the HTTP request completes, the data is fetched, and the
.then()callback is added to the queue.The event loop moves the callback from the queue to the stack again.
The data is processed and
console.log("5. Security system status:", data.status)is executed.
Event Loop - Detailed Analysis
To better understand the event loop, let's draw its main components:
βββββββββββββββ βββββββββββββ βββββββββββββββββββββ
β β β β β β
β Call Stack β β Web APIs β β Callback Queue β
β β β β β β
βββββββββββββββ βββββββββββββ βββββββββββββββββββββ
β β β
β β β
β ββββββββββ β
ββββββββββββββ Event ββββββββββββββββ
β Loop β
ββββββββββIn the graphical representation:
- Call Stack - a LIFO (Last In, First Out) stack storing function calls currently being executed
- Web APIs - browser/environment interfaces for asynchronous operations (setTimeout, fetch, Event Listeners)
- Callback Queue - a FIFO (First In, First Out) queue storing callbacks ready to execute
- Event Loop - continuously checks whether the call stack is empty, and if so, moves functions from the queue to the stack
The amazing thing is that all of this runs on a single thread! JavaScript does not execute these tasks in parallel, but switches between them in a way that appears as if everything is happening simultaneously.
Microtasks and Macrotasks
In newer JavaScript implementations (and the specification) we distinguish two types of queues:
- Microtask Queue - for higher-priority tasks, such as Promise callbacks
- Macrotask Queue / Task Queue - for lower-priority tasks, such as setTimeout, setInterval, I/O
When the stack is empty, all tasks from the microtask queue are executed first, then from the macrotask queue.
console.log("1. Starting the morning dinosaur feeding.");
// Macrotask (setTimeout)
setTimeout(() => {
console.log("4. Checking dinosaur health status.");
}, 0);
// Microtask (Promise)
Promise.resolve().then(() => {
console.log("3. Reading data from the security system.");
});
console.log("2. Preparing food for the predators.");Result:
1. Starting the morning dinosaur feeding.
2. Preparing food for the predators.
3. Reading data from the security system.
4. Checking dinosaur health status.Notice that although both asynchronous tasks (setTimeout with 0ms and Promise.resolve()) are ready to execute almost immediately, the Promise (microtask) executes before the setTimeout (macrotask).
Blocking the Event Loop
Because JavaScript is single-threaded, long-running operations can "block" the event loop, stopping other tasks from executing. It is like the situation where the control center worker gets stuck at one monitor and cannot check the other systems.
console.log("Starting dinosaur growth simulation...");
// Function that blocks execution for 5 seconds
function heavyComputation() {
const startTime = Date.now();
while (Date.now() - startTime < 5000) {
// Intensive computations...
}
}
heavyComputation();
console.log("Simulation complete!"); // After 5 seconds
// This code will not execute for 5 seconds, even though it is asynchronous!
setTimeout(() => {
console.log("Checking security systems...");
}, 1000);In this example the heavyComputation() function blocks the JavaScript thread for 5 seconds. During this time no other tasks can be executed, including asynchronous ones. It is like the park worker getting stuck on one task and not being able to respond to alarms or other important signals.
In a real Jurassic Park such blocking could be catastrophic - a raptor could escape and the system would not register it because it is busy with something else!
That is why in JavaScript we try to:
- Avoid long synchronous operations
- Split complex computations into smaller pieces
- Use Web Workers for CPU-intensive operations
Task Execution Order - Practical Example
Let's analyze a more complex example that shows the order of execution of different task types in Jurassic Park:
// Jurassic Park control system simulation
console.log("1. Starting the Jurassic Park control system...");
// Macrotask (setTimeout)
setTimeout(() => {
console.log("6. Checking electric fences...");
// Nested microtask inside macrotask
Promise.resolve().then(() => {
console.log("7. Verifying predator status...");
});
}, 0);
// Microtask (Promise)
Promise.resolve().then(() => {
console.log("3. Initializing security cameras...");
// Nested microtask
Promise.resolve().then(() => {
console.log("4. Calibrating motion sensors...");
});
});
// Another microtask
Promise.resolve().then(() => {
console.log("5. Starting emergency protocols...");
});
// Synchronous code
console.log("2. Checking system status...");Result:
1. Starting the Jurassic Park control system...
2. Checking system status...
3. Initializing security cameras...
4. Calibrating motion sensors...
5. Starting emergency protocols...
6. Checking electric fences...
7. Verifying predator status...This example shows that:
- Synchronous code executes first (1, 2)
- Then all microtask queue tasks execute (3, 4, 5)
- Only then do macrotask queue tasks execute (6)
- Microtasks created during a macrotask (7) execute immediately after the current macrotask finishes
Bonus: Var, Let, Const - When to Use Which?
When working with asynchronous code it is important to declare variables correctly. The way of declaration affects their behavior in blocks and functions, which directly impacts asynchronous code (e.g., variables in loops with setTimeout). Just as the park has different types of fences for different dinosaur types (electric for T-Rex, standard for Triceratops), in JavaScript we have different ways to declare variables: var, let, and const.
Const - Always the Default Choice
const means a constant - a value that cannot be reassigned. In Jurassic Park we use const for things that should not change, like safety parameters or system configuration:
// System configuration - should not change
const MAX_DINOSAURS_PER_ENCLOSURE = 5;
const FENCE_MINIMUM_VOLTAGE = 10000; // volts
const EMERGENCY_CONTACT = "+1-555-JURASSIC";
// Trying to change a const will throw an error
MAX_DINOSAURS_PER_ENCLOSURE = 10; // TypeError: Assignment to constant variableWhen to use const:
- For values that will not change
- For objects and arrays (even if their contents change)
- As the default choice - when in doubt, use
const
Important: const does not mean the contents of an object or array are immutable!
// This is fine - we modify the contents, not the assignment
const dinosaurs = [];
dinosaurs.push({ name: "Rexy", species: "T-Rex" }); // OK!
dinosaurs.push({ name: "Blue", species: "Velociraptor" }); // OK!
const parkConfig = {
openTime: "09:00",
closeTime: "18:00"
};
parkConfig.closeTime = "20:00"; // OK - modifying a property
// This will throw an error - trying to reassign
dinosaurs = []; // TypeError!
parkConfig = {}; // TypeError!Let - When the Value Changes
let is used when a variable's value will change during program execution. In Jurassic Park we use let for dynamic things like counters, accumulators, or loop variables:
// Visitor counter - changes throughout the day
let visitorCount = 0;
function addVisitors(count) {
visitorCount += count;
console.log(`Current visitor count: ${visitorCount}`);
}
addVisitors(50); // 50
addVisitors(30); // 80
addVisitors(20); // 100When to use let:
- In loops (for, while)
- For counters and accumulators
- When the value will be reassigned
// Loops - classic use case for let
for (let i = 0; i < 5; i++) {
console.log(`Checking dinosaur #${i}`);
}
// Accumulators
let totalFeedingCost = 0;
const dinosaurs = [
{ name: "Rexy", dailyFoodCost: 500 },
{ name: "Blue", dailyFoodCost: 150 },
{ name: "Trixie", dailyFoodCost: 200 }
];
for (const dino of dinosaurs) {
totalFeedingCost += dino.dailyFoodCost;
}
console.log(`Total feeding cost: $${totalFeedingCost}`);Var - Almost Never (Legacy Code)
var is the old way of declaring variables in JavaScript. It has problematic behavior and should not be used in modern code. The only time you will see var is in old (legacy) code written before 2015 (before ES6).
Problems with var:
- Function scope instead of block scope -
var"escapes" from blocks
// Problem: var ignores blocks
function checkDinosaur(isDangerous) {
if (isDangerous) {
var alert = "DANGER!"; // var is accessible outside the if block!
}
console.log(alert); // "DANGER!" - leaks out of the if block!
// With let/const we would get a ReferenceError
}
checkDinosaur(true);
// Compare with let:
function checkDinosaurProper(isDangerous) {
if (isDangerous) {
let alert = "DANGER!";
}
console.log(alert); // ReferenceError: alert is not defined
}- Hoisting with undefined -
varis "hoisted" to the top of the function
// Strange var behavior
function feedDinosaurs() {
console.log(food); // undefined (not ReferenceError!)
var food = "meat";
console.log(food); // "meat"
}
// This is interpreted as:
function feedDinosaurs() {
var food; // hoisting - declaration at the top
console.log(food); // undefined
food = "meat"; // assignment
console.log(food); // "meat"
}- Can be redeclared - you can accidentally overwrite variables
var dinosaurName = "Rexy";
// Accidentally using the same name
var dinosaurName = "Blue"; // No error! Overwrote the previous value
console.log(dinosaurName); // "Blue" - Rexy is gone!
// With let/const:
let dinoName = "Rexy";
let dinoName = "Blue"; // SyntaxError: Identifier 'dinoName' has already been declaredWhen to use var:
- Never in new code
- Only when editing very old code and you must maintain compatibility
Practical Example - Code Review
Imagine you receive code from a colleague for review. Here is how to improve variable usage:
Bad code (before):
// Bad - everything with var
var parkName = "Jurassic Park"; // Does not change - should be const
var isOpen = true; // Changes - should be let
var maxCapacity = 10000; // Does not change - should be const
function processVisitors() {
var totalVisitors = 0; // Accumulator - should be let
for (var i = 0; i < 100; i++) { // Iterator - should be let
totalVisitors++;
}
console.log(i); // 100 - var leaks! Problem!
return totalVisitors;
}Good code (after):
// Good - using const as default
const parkName = "Jurassic Park";
const maxCapacity = 10000;
// let only when the value changes
let isOpen = true;
function processVisitors() {
// let for accumulator
let totalVisitors = 0;
// let in loop - block scoped
for (let i = 0; i < 100; i++) {
totalVisitors++;
}
// console.log(i); // ReferenceError - i is scoped to the loop
return totalVisitors;
}
// We can change isOpen
isOpen = false;
isOpen = true;
// But we cannot change const
// parkName = "Dino World"; // TypeError!Another Example - Dinosaur Management System
class DinosaurManagementSystem {
constructor() {
// const for properties whose references do not change
this.dinosaurs = []; // array contents may change, but reference does not
this.config = { // object contents may change, but reference does not
maxDinosaurs: 50,
securityLevel: "high"
};
}
addDinosaur(name, species, dangerLevel) {
// const for function parameters and local values that do not change
const newDinosaur = {
id: Date.now(),
name,
species,
dangerLevel,
status: "active"
};
this.dinosaurs.push(newDinosaur);
return newDinosaur;
}
getDangerousCount() {
// let for accumulator
let count = 0;
// const in for...of when we do not modify the loop variable
for (const dino of this.dinosaurs) {
if (dino.dangerLevel > 7) {
count++; // we modify count, hence let
}
}
return count;
}
calculateDailyFoodCost() {
// let for values that change
let totalCost = 0;
// let in classic for loop
for (let i = 0; i < this.dinosaurs.length; i++) {
const dino = this.dinosaurs[i]; // const - we do not reassign the reference
// const for computed values
const dailyCost = this.calculateDinosaurFoodCost(dino);
totalCost += dailyCost;
}
return totalCost;
}
calculateDinosaurFoodCost(dinosaur) {
// const for all values that do not change
const baseCost = 50;
const costMultiplier = dinosaur.dangerLevel > 5 ? 2 : 1;
const dailyCost = baseCost * costMultiplier;
return dailyCost;
}
}
// Usage example
const parkSystem = new DinosaurManagementSystem(); // const - reference does not change
parkSystem.addDinosaur("Rexy", "T-Rex", 9);
parkSystem.addDinosaur("Blue", "Velociraptor", 8);
parkSystem.addDinosaur("Trixie", "Triceratops", 3);
// let for values that will change
let dangerousCount = parkSystem.getDangerousCount();
console.log(`Dangerous dinosaurs: ${dangerousCount}`);
// const for one-time-use values
const foodCost = parkSystem.calculateDailyFoodCost();
console.log(`Daily food cost: $${foodCost}`);
// We can add more dinosaurs
parkSystem.addDinosaur("Delta", "Velociraptor", 8);
// And recalculate
dangerousCount = parkSystem.getDangerousCount(); // let allows reassignment
console.log(`Dangerous dinosaurs: ${dangerousCount}`);Rule of Thumb
- Always start with
const- if the compiler/linter complains that you are trying to change the value, switch tolet - Use
letonly when you have to - loops, counters, accumulators - Never use
var- unless editing old code
// Good practice
const maxDinosaurs = 50;
let currentDinosaurs = 0;
for (let i = 0; i < maxDinosaurs; i++) {
const dinosaur = createDinosaur();
currentDinosaurs++;
}
// Bad practice
var maxDinosaurs = 50;
var currentDinosaurs = 0;
for (var i = 0; i < maxDinosaurs; i++) {
var dinosaur = createDinosaur();
currentDinosaurs++;
}Why Does This Matter?
Just as proper fences in Jurassic Park prevent dinosaur escapes, proper use of const and let prevents bugs in code:
- Readability - you can immediately see which values change (
let) and which do not (const) - Safety -
constprotects against accidental modification - Block scope - variables do not "leak" out of blocks
- Easier debugging - fewer surprises from hoisting
Remember: in modern JavaScript, var is like dinosaurs - an interesting relic of the past, but you do not want it in your production code!
Summary
The JavaScript event model (event loop) is the key to understanding how this single-threaded language can handle many asynchronous operations - essential in applications like the Jurassic Park management system.
Remember the key principles:
- JavaScript is single-threaded but asynchronous
- The event loop allows handling many tasks without blocking the user interface
- Tasks execute in a defined order: synchronous β microtasks β macrotasks
- Avoid blocking the event loop with long synchronous operations
In the next lessons we will see how to use this knowledge to write efficient asynchronous code using callbacks, Promises, and async/await.
Code for this lesson: index.js
// Event Loop and asynchronicity in Jurassic Park
console.log("Jurassic Park Control Center - Event Loop Demo");
console.log("Simulation of asynchronous park management system\n");
// ===========================================
// 1. Event Loop basics - Call Stack
// ===========================================
console.log("=== 1. CALL STACK - Execution order ===");
function checkFence() {
console.log("1. Checking the T-Rex fence...");
return "Fence secure";
}
function checkDinosaur() {
console.log("2. Checking the dinosaur's condition...");
const result = checkFence(); // Synchronous call
console.log("3. " + result);
return "Dinosaur safe";
}
function securityReport() {
console.log("0. Starting security report");
const status = checkDinosaur();
console.log("4. Report: " + status);
}
// Synchronous execution - call stack
securityReport();
// ===========================================
// 2. setTimeout - Callback Queue
// ===========================================
console.log("\n=== 2. SETTIMEOUT - Asynchronous operations ===");
console.log("A. Starting park monitoring...");
setTimeout(() => {
console.log("C. Alarm! Movement detected in the T-Rex enclosure!");
}, 2000);
setTimeout(() => {
console.log("D. Automatic system: Additional safeguards activated");
}, 1000);
console.log("B. Continuing other tasks...");
// ===========================================
// 3. Park sensor simulation
// ===========================================
console.log("\n=== 3. PARK SENSOR SIMULATION ===");
class DinosaurSensor {
constructor(name, dinosaur) {
this.name = name;
this.dinosaur = dinosaur;
this.isActive = true;
}
checkStatus(callback) {
console.log(`Sensor ${this.name}: Checking ${this.dinosaur}...`);
// Simulating sensor delay
const delay = Math.random() * 3000 + 1000; // 1-4 seconds
setTimeout(() => {
const status = Math.random() > 0.8 ? 'ALARM' : 'SAFE';
const report = {
sensor: this.name,
dinosaur: this.dinosaur,
status: status,
time: new Date().toLocaleTimeString()
};
callback(report);
}, delay);
}
}
// Callback hell - problem with nested callbacks
function monitorPark() {
console.log("\nStarting park monitoring...");
const sensorTRex = new DinosaurSensor("TR-001", "T-Rex");
const sensorVelociraptor = new DinosaurSensor("VR-002", "Velociraptor");
const sensorTriceratops = new DinosaurSensor("TC-003", "Triceratops");
// Callback hell - each sensor one by one
sensorTRex.checkStatus((reportTRex) => {
console.log("T-Rex report:", reportTRex);
sensorVelociraptor.checkStatus((reportVelo) => {
console.log("Velociraptor report:", reportVelo);
sensorTriceratops.checkStatus((reportTrice) => {
console.log("Triceratops report:", reportTrice);
// Analysis of all reports
const reports = [reportTRex, reportVelo, reportTrice];
const alarms = reports.filter(r => r.status === 'ALARM');
if (alarms.length > 0) {
console.log("WARNING! Alarms detected:", alarms.length);
alarms.forEach(alarm => {
console.log(` ${alarm.dinosaur} - ${alarm.status}`);
});
} else {
console.log("All dinosaurs safe");
}
});
});
});
}
// Start monitoring after 3 seconds
setTimeout(monitorPark, 3000);
// ===========================================
// 4. Promises - solving Callback Hell
// ===========================================
console.log("\n=== 4. PROMISES - Better asynchronous management ===");
class ModernSensor {
constructor(name, dinosaur) {
this.name = name;
this.dinosaur = dinosaur;
}
checkStatus() {
return new Promise((resolve, reject) => {
console.log(`Promise: Checking ${this.dinosaur}...`);
const delay = Math.random() * 2000 + 500;
setTimeout(() => {
const success = Math.random() > 0.1; // 90% chance of success
if (success) {
const status = Math.random() > 0.7 ? 'ALARM' : 'SAFE';
resolve({
sensor: this.name,
dinosaur: this.dinosaur,
status: status,
time: new Date().toLocaleTimeString()
});
} else {
reject(new Error(`Sensor ${this.name} is not responding`));
}
}, delay);
});
}
}
function monitorParkPromises() {
console.log("\nPromise-based monitoring...");
const modernTRex = new ModernSensor("MTR-001", "Modern T-Rex");
const modernVelo = new ModernSensor("MVR-002", "Modern Velociraptor");
const modernTrice = new ModernSensor("MTC-003", "Modern Triceratops");
// Promise chain
modernTRex.checkStatus()
.then(report => {
console.log("Promise T-Rex:", report);
return modernVelo.checkStatus();
})
.then(report => {
console.log("Promise Velociraptor:", report);
return modernTrice.checkStatus();
})
.then(report => {
console.log("Promise Triceratops:", report);
console.log("All Promise sensors checked!");
})
.catch(error => {
console.log("Error in Promise chain:", error.message);
});
// Promise.all - all at once
console.log("\nPromise.all - parallel checking...");
Promise.all([
modernTRex.checkStatus(),
modernVelo.checkStatus(),
modernTrice.checkStatus()
])
.then(reports => {
console.log("All Promise.all reports ready:");
reports.forEach(report => {
console.log(` ${report.dinosaur}: ${report.status}`);
});
const alarms = reports.filter(r => r.status === 'ALARM');
if (alarms.length > 0) {
console.log(`Promise.all: ${alarms.length} alarms!`);
} else {
console.log("Promise.all: Park safe!");
}
})
.catch(error => {
console.log("Promise.all error:", error.message);
});
}
// Start Promise monitoring after 8 seconds
setTimeout(monitorParkPromises, 8000);
// ===========================================
// 5. Async/Await - cleanest approach
// ===========================================
console.log("\n=== 5. ASYNC/AWAIT - Modern asynchronous JavaScript ===");
class AsyncSensor {
constructor(name, dinosaur) {
this.name = name;
this.dinosaur = dinosaur;
}
async checkStatus() {
console.log(`Async: Checking ${this.dinosaur}...`);
const delay = Math.random() * 1500 + 500;
// Async/await with a Promise
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.05; // 95% success
if (success) {
const status = Math.random() > 0.6 ? 'ALARM' : 'SAFE';
resolve({
sensor: this.name,
dinosaur: this.dinosaur,
status: status,
time: new Date().toLocaleTimeString(),
delay: delay.toFixed(0) + 'ms'
});
} else {
reject(new Error(`Async sensor ${this.name} error`));
}
}, delay);
});
}
}
// Async function
async function monitorParkAsync() {
console.log("\nAsync/Await monitoring started...");
try {
const asyncTRex = new AsyncSensor("ATR-001", "Async T-Rex");
const asyncVelo = new AsyncSensor("AVR-002", "Async Velociraptor");
const asyncTrice = new AsyncSensor("ATC-003", "Async Triceratops");
// Sequentially (one after another)
console.log("Sequential checking:");
const reportTRex = await asyncTRex.checkStatus();
console.log(" Async T-Rex:", reportTRex);
const reportVelo = await asyncVelo.checkStatus();
console.log(" Async Velociraptor:", reportVelo);
const reportTrice = await asyncTrice.checkStatus();
console.log(" Async Triceratops:", reportTrice);
// Parallel with Promise.all
console.log("\nParallel checking async/await:");
const [reportT2, reportV2, reportTr2] = await Promise.all([
asyncTRex.checkStatus(),
asyncVelo.checkStatus(),
asyncTrice.checkStatus()
]);
const allReports = [reportT2, reportV2, reportTr2];
console.log("Parallel results:");
allReports.forEach(report => {
console.log(` ${report.dinosaur}: ${report.status} (${report.delay})`);
});
// Security analysis
const dangerous = allReports.filter(r => r.status === 'ALARM');
if (dangerous.length > 0) {
console.log(`\nASYNC ALERT: ${dangerous.length} dinosaurs need attention!`);
dangerous.forEach(dino => {
console.log(` ${dino.dinosaur} - intervention required`);
});
} else {
console.log("\nASYNC SUCCESS: All dinosaurs under control!");
}
} catch (error) {
console.log("Async/await error:", error.message);
}
}
// Start async monitoring after 15 seconds
setTimeout(monitorParkAsync, 15000);
// ===========================================
// 6. Event Loop in practice - Microtasks vs Macrotasks
// ===========================================
console.log("\n=== 6. EVENT LOOP - Execution order ===");
function eventLoopDemo() {
console.log("\nEvent Loop demo - execution order:");
console.log("1. Synchronous code");
setTimeout(() => {
console.log("4. setTimeout (Macro task)");
}, 0);
Promise.resolve().then(() => {
console.log("3. Promise.then (Micro task)");
});
console.log("2. Synchronous code - end");
// Order: 1, 2, 3, 4
// Microtasks (Promise) have higher priority than macrotasks (setTimeout)
}
eventLoopDemo();
// ===========================================
// 7. Practical example - Park alert system
// ===========================================
console.log("\n=== 7. PARK ALERT SYSTEM ===");
class ParkAlertSystem {
constructor() {
this.alerts = [];
this.isMonitoring = false;
}
async startMonitoring() {
this.isMonitoring = true;
console.log("Alert system started monitoring...");
while (this.isMonitoring) {
await this.checkSystems();
await this.wait(2000); // Check every 2 seconds
}
}
stopMonitoring() {
this.isMonitoring = false;
console.log("βΉMonitoring stopped");
}
async checkSystems() {
const systems = ['fences', 'power', 'communication', 'security'];
const promises = systems.map(system => this.checkSystem(system));
try {
const results = await Promise.allSettled(promises);
results.forEach((result, index) => {
const systemName = systems[index];
if (result.status === 'fulfilled') {
if (result.value.status === 'ALARM') {
this.addAlert(systemName, result.value.message);
}
} else {
this.addAlert(systemName, `System error: ${result.reason}`);
}
});
if (this.alerts.length > 0) {
this.displayAlertsAndClear();
}
} catch (error) {
console.log("Critical monitoring error:", error);
}
}
async checkSystem(system) {
const delay = Math.random() * 1000 + 200;
return new Promise((resolve, reject) => {
setTimeout(() => {
const isWorking = Math.random() > 0.2; // 80% chance of working
if (isWorking) {
const hasAlert = Math.random() > 0.8; // 20% chance of an alert
resolve({
system,
status: hasAlert ? 'ALARM' : 'OK',
message: hasAlert ? `Problem with system ${system}` : `System ${system} is working correctly`
});
} else {
reject(`System ${system} is not responding`);
}
}, delay);
});
}
addAlert(system, message) {
this.alerts.push({
system,
message,
time: new Date().toLocaleTimeString()
});
}
displayAlertsAndClear() {
console.log(`\nPARK ALERT (${this.alerts.length} problems):`);
this.alerts.forEach(alert => {
console.log(` [${alert.time}] ${alert.system}: ${alert.message}`);
});
this.alerts = []; // Clear after display
}
async wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Alert system test
const alertSystem = new ParkAlertSystem();
// Start the system after 20 seconds for 10 seconds
setTimeout(async () => {
await alertSystem.startMonitoring();
// Stop after 10 seconds
setTimeout(() => {
alertSystem.stopMonitoring();
}, 10000);
}, 20000);
// ===========================================
// 8. Event Loop summary
// ===========================================
setTimeout(() => {
console.log("\n" + "=".repeat(50));
console.log("EVENT LOOP SUMMARY:");
console.log("1. JavaScript is single-threaded");
console.log("2. The Event Loop enables asynchronicity");
console.log("3. Callbacks β Promises β Async/Await");
console.log("4. Microtasks have higher priority than Macrotasks");
console.log("5. Async/Await is the cleanest syntax");
console.log("=".repeat(50));
}, 35000);Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the Event Loop in JavaScript?