Module 46 // Core JavaScript

Advanced Async Control Flow

Module Objective

Debounce, throttle, retries, backoff, cancellation

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Implementation of Debounce
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

// Result: Only runs after 500ms of "silence"
💡 Debouncing is essential for search bars or resizing listeners where you only want to act after the user has stopped typing or dragging.
// Example 2
// 2. The Retry Pattern
async function fetchWithRetry(url, count = 3) {
  for (let i = 0; i < count; i++) {
    try {
      return await fetch(url);
    } catch (err) {
      if (i === count - 1) throw err;
      await new Promise(r => setTimeout(r, 1000 * (i + 1))); // Exponential backoff
    }
  }
}
💡 In distributed systems, networking is unreliable. Retrying with exponential backoff reduces load on the server while increasing success rates.
// Example 3
// 3. Parallel Limit
// Managing thousands of requests without 
// crashing the CPU or Browser.
async function batchProcess(urls, limit = 5) {
  // Use a Worker or a custom queue to limit 
  // active promises to 'limit' at a time.
}
💡 Sometimes running too many things in parallel is bad. Limiting concurrency ensures that the browser doesn't run out of memory or network sockets.

Engine & Memory Architecture

Async Resource Management

1. Timer Management:

  • setTimeout creates entries in the engine's Timer Table.
  • Debouncing heavy tasks prevents "Timer Overflow" and saves CPU cycles.

2. Garbage Collection (Aborted Requests):

  • When you use AbortController, the engine can reclaim the Memory used by the network buffer much earlier than waiting for a timeout.

3. Closure Persistance:

  • Async wrappers (like debounce) use Closures to store the timer ID.
  • This keeps the variable in the Heap across many events, allowing the function to "remember" the previous state.