Asynchronous Behavior

> Promises, `setTimeout`, `fetch`, etc. This is where JavaScript *diverges* from LiveCode. Take this:

console.log("A"); setTimeout(() => { console.log("B"); }, 1000); console.log("C");

Output:

A C B

Here is a flow diagram:

digraph AsyncExecution { rankdir=TB; node [shape=box, style=filled, fontname=Helvetica]; CallStack [label="Call Stack", fillcolor=lightblue]; WebAPI [label="Web APIs\n(e.g. setTimeout)", fillcolor=lightgreen]; CallbackQueue [label="Callback Queue\n(Macrotask Queue)", fillcolor=lightcoral]; EventLoop [label="Event Loop", shape=ellipse, style=solid]; A [label="console.log('A')"]; Timeout [label="setTimeout(...)"]; C [label="console.log('C')"]; B [label="callback → console.log('B')"]; CallStack -> A; A -> Timeout; Timeout -> C; Timeout -> WebAPI; WebAPI -> B [label="after 2s", style=dashed]; B -> CallbackQueue; EventLoop -> B [label="moves to stack"]; CallStack -> EventLoop; }

## Key concept: * Asynchronous code is **not executed immediately** * It is **scheduled** to run **later**, using an internal **Event Loop** * Meanwhile, JavaScript **keeps going** (non-blocking) Think of it like a `send "foo" to me in 1 second` in LiveCode, except: * JavaScript’s event loop is always running * Delayed tasks go into a **callback queue** > ❗ Regular function calls: synchronous > ❗ Asynchronous functions (`setTimeout`, `fetch`, `Promise.then`): scheduled and delayed

Why? Because `setTimeout` is **asynchronous**.

# See