Skip to content

Mishaelx6/Event-loop-visualizer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Event Loop Visualizer

A comprehensive visual tool to understand and demonstrate JavaScript's event loop mechanism with real-time monitoring and interactive examples.

🎯 Description

This project provides an interactive visualization of how JavaScript's event loop works, including the call stack, task queue, microtask queue, and Web APIs. It features both server-side demonstrations and real-time WebSocket broadcasting for educational purposes.

✨ Features

  • πŸ”„ Real-time Event Loop Monitoring - Live visualization of event loop operations
  • πŸ“‘ WebSocket Broadcasting - Real-time updates to connected dashboard clients
  • 🎨 Colored Logging System - Color-coded console output for different operation types
  • πŸ§ͺ Interactive Endpoints - Multiple demonstration scenarios
  • πŸ“Š Blocking Detection - Detects and reports event loop blocking
  • πŸƒ Race Condition Demos - Shows operation interleaving
  • πŸ“± Responsive Dashboard - Web-based interface for monitoring

πŸš€ Getting Started

Prerequisites

  • Node.js (v14 or higher)
  • npm or yarn package manager

Installation

# Clone the repository
git clone https://github.com/Mishaelx6/Event-loop-visualizer.git
cd Event-loop-visualizer

# Install dependencies
npm install

Usage

# Start the server
npm start

# For development with auto-restart
npm run dev

The server will start on:

  • HTTP Server: http://localhost:3000
  • WebSocket Server: ws://localhost:3001

πŸ“ Project Structure

Event-loop-visualizer/
β”œβ”€β”€ server.js                 # Main Express server with WebSocket support
β”œβ”€β”€ package.json             # Dependencies and scripts
β”œβ”€β”€ package-lock.json        # Locked dependency versions
β”œβ”€β”€ .gitignore              # Git ignore rules
β”œβ”€β”€ README.md               # This documentation
β”œβ”€β”€ public/                 # Static web assets
β”‚   └── index.html         # Main dashboard HTML
β”œβ”€β”€ styles/                 # CSS stylesheets
β”‚   └── main.css          # Main styling
└── src/                   # Client-side JavaScript
    └── main.js            # Frontend visualization logic

πŸ”§ API Endpoints

Dashboard

  • **GET / - Main dashboard with all endpoint links and documentation

Event Loop Demonstrations

1. Blocking Operations

GET /blocking/:time
  • Blocks the event loop for specified milliseconds
  • Demonstrates synchronous blocking behavior
  • Example: /blocking/3000 (blocks for 3 seconds)

2. Non-blocking setTimeout

GET /setTimeout/:time
  • Uses setTimeout for non-blocking delays
  • Shows macrotask scheduling
  • Example: /setTimeout/2000

3. Execution Order

GET /order-of-execution
  • Demonstrates microtask vs macrotask priority
  • Shows process.nextTick, Promise.then, setImmediate, setTimeout order
  • Returns JSON with expected execution order

4. Non-blocking I/O Simulation

GET /nonblocking-io
  • Simulates async I/O operations using Promises
  • Demonstrates non-blocking behavior
  • 2-second simulated I/O delay

5. Complex Mixed Operations

GET /complex
  • Real-world scenario with multiple async operations
  • Combines CPU tasks, database queries, and file operations
  • Shows coordination of different operation types

6. Race Condition Demo

GET /race-demo
  • Demonstrates operation interleaving
  • Shows microtasks executing before macrotasks
  • Random delays for realistic race conditions

7. Event Loop Blocking Detection

GET /detect-blocking
  • Monitors event loop health in real-time
  • Detects and reports blocking operations
  • Shows timing delays and performance issues

🎨 Color Coding System

The logging system uses color-coded output for different operation types:

Color Type Description
πŸ”΅ Blue event-loop General event loop activity
🟣 Magenta microtask Promise.then, process.nextTick
🟑 Yellow macrotask setTimeout, setImmediate
πŸ”΄ Red blocking Synchronous blocking operations
🟠 Orange cpu CPU-intensive tasks
🟒 Green async Async operation completion
πŸ”΅ Cyan io I/O operations
πŸ”΄ Bright Red error Error conditions and blocking detection

πŸ“‘ WebSocket Integration

Connection

// Connect to real-time monitoring
const ws = new WebSocket('ws://localhost:3001');

ws.onopen = () => console.log('Connected to event loop monitor');
ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log(`${data.timestamp} [${data.type}] ${data.message}`);
};

Message Format

{
    "timestamp": "13:25:42.581",
    "type": "blocking",
    "message": "Starting potentially blocking operation", 
    "requestId": 1
}

πŸ§ͺ Testing and Examples

Basic Testing

# Test blocking behavior
curl http://localhost:3000/blocking/1000

# Test non-blocking behavior
curl http://localhost:3000/setTimeout/1000

# Test complex scenario
curl http://localhost:3000/complex

Browser Testing

  1. Open http://localhost:3000 in browser
  2. Open browser console (F12)
  3. Click on endpoint links
  4. Observe colored logs and timing

WebSocket Dashboard Testing

  1. Connect multiple browser tabs to ws://localhost:3001
  2. Make requests to endpoints
  3. Observe real-time updates in all connected clients

πŸ” Monitoring and Debugging

Event Loop Health

  • Monitor for delays >100ms (indicates blocking)
  • Watch for microtask queue buildup
  • Track macrotask scheduling delays

Performance Indicators

  • Normal: Operations complete within expected timeframes
  • Warning: Delays between 100-500ms
  • Critical: Delays >500ms indicate severe blocking

πŸ› οΈ Development

Scripts

{
    "start": "node server.js",
    "dev": "nodemon server.js", 
    "build": "webpack --mode production",
    "test": "jest"
}

Adding New Endpoints

app.get('/your-endpoint', (req, res) => {
    logWithColour('Your operation', 'type', req.id);
    // Your logic here
    res.send('Response');
});

πŸ“š Educational Concepts Demonstrated

Event Loop Phases

  1. Timer Phase - setTimeout, setInterval callbacks
  2. Pending Callbacks - I/O callbacks
  3. Idle, Prepare - Internal preparation
  4. Poll Phase - New I/O events
  5. Check Phase - setImmediate callbacks
  6. Close Callbacks - Socket cleanup

Task Priorities

  1. Synchronous Code - Highest priority
  2. Microtasks - Next after sync code
  3. Macrotasks - Next event loop iteration

Common Patterns

  • Callback Hell - Nested callbacks
  • Promise Chains - Sequential async operations
  • Async/Await - Modern async handling
  • Event Emitters - Event-driven architecture

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow existing code style
  • Add comprehensive logging
  • Test with different scenarios
  • Update documentation

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ”— Related Resources

πŸ“ž Support

For issues, questions, or contributions:

  • Create an issue on GitHub
  • Check existing documentation
  • Review console logs for debugging

Built with ❀️ for JavaScript education and event loop understanding

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors