Asynchronous Callbacks
What you'll learn: How callbacks can be executed later, outside the normal flow of your code.
The Core Idea
You've seen synchronous callbacks that run immediately when the outer function calls them. Asynchronous callbacks are different: they're stored by the JavaScript environment and invoked later, after some event occurs (like a timer finishing or data arriving).
Functions like setTimeout take your callback and schedule it to run after a delay. Your callback doesn't execute right away—it gets queued up and runs when the event loop picks it off the task queue.
A Real-World Analogy
Think of ordering food at a restaurant. With synchronous callbacks, the waiter asks a question and you answer immediately. With asynchronous callbacks, you place an order and the waiter walks away—the kitchen prepares your meal in the background, and the waiter brings it back later when it's ready.
How It Works
console.log("Start");
setTimeout(function() {
console.log("This runs later");
}, 1000);
console.log("End");
Output:
Start
End
This runs later
Even though setTimeout appears in the middle, its callback doesn't run until after the rest of your code finishes—and after the 1000ms delay.
Why This Matters
Asynchronous callbacks keep JavaScript responsive. While waiting for a timer, network request, or file read, your program can keep running other code instead of freezing.
Key Takeaway: Asynchronous callbacks are scheduled to run later by the JavaScript environment, not during the current execution flow—they're invoked after the event loop processes the task queue.