Search lands in PR-5.1 (Pagefind).

Explanation Intermediate

Chapter 7 Updated

Sync, Async & the magic of setTimeout(0)

Sync methods freeze the event loop, crypto can block for seconds, and setTimeout(0) still waits for the call stack.

  • Full 20m
  • Revision 5m
  • Flow 2m

Sync code → call stack empty → libuv callbacks

flowchart TD
    Start["<b>i · Sync code starts</b><br/>console.log(Hello World)<br/>var assignments"]
      --> Block["<b>ii · pbkdf2Sync</b><br/>BLOCKS main thread<br/>(50M iterations)"]
    Block --> AfterBlock["<b>iii · After sync crypto</b><br/>console.log(First Key)"]
    AfterBlock --> Offload["<b>iv · Async offloads</b><br/>setTimeout(0) → timer queue<br/>pbkdf2() → libuv thread pool"]
    Offload --> MoreSync["<b>v · More sync code</b><br/>multiplyFn + console.log"]
    MoreSync --> Empty{"<b>vi · Call stack empty?</b>"}
    Empty -- "yes" --> Loop["<b>vii · Event loop takes over</b>"]
    Loop --> Timer["<b>viii · Timer callback</b><br/>call me right now !!!!"]
    Timer --> Pool["<b>ix · Thread pool callback</b><br/>Second Key is generated"]
 
    classDef sync fill:#f5efe1,stroke:#6a8a4f,stroke-width:2px,color:#1a1915;
    classDef block fill:#fdecd3,stroke:#c2410c,stroke-width:2px,color:#1a1915;
    classDef loop fill:#eaf2f8,stroke:#3a6ea5,stroke-width:2px,color:#1a1915;
    classDef cb fill:#ece5f5,stroke:#6b46c1,stroke-width:2px,color:#1a1915;
    class Start,AfterBlock,MoreSync sync
    class Block,Offload block
    class Empty,Loop loop
    class Timer,Pool cb
  • Sync starts

    V8 pushes GEC, prints "Hello World", assigns `a` and `b` on the call stack.

  • pbkdf2Sync blocks

    Main thread frozen for seconds while V8 computes 50M iterations — event loop cannot advance.

  • Post-block sync

    Once pbkdf2Sync returns, `"First Key is Generated"` prints immediately.

  • Async offloads

    setTimeout(0) → libuv timer queue; pbkdf2() → libuv thread pool. V8 does not wait.

  • More sync

    `multiplyFn()` runs on the call stack, then `"Multiplication result…"` prints.

  • Stack empty

    GEC pops. V8 is idle — the call stack is finally empty.

  • Event loop

    libuv’s event loop starts pushing ready callbacks back onto the call stack.

  • Timer callback

    setTimeout(0) callback fires from the timer queue — `"call me right now !!!!"`.

  • Thread pool cb

    Async pbkdf2 finishes on a worker thread; libuv delivers `"Second Key is generated"`.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.