Callback Queues
You'll learn how to use closures to store and batch-execute multiple callback functions for deferred or coordinated processing.
What Are Callback Queues?
A callback queue is an array of functions maintained in closure scope that you accumulate over time and then execute all at once (or in a controlled sequence). Instead of calling functions immediately, you collect them for later use—useful for batching operations, coordinating multiple async tasks, or implementing publish-subscribe patterns.
Think of it like a to-do list: instead of doing every task as soon as someone mentions it, you write them all down first, then work through the list when you're ready.
How It Works
You create a private array inside a closure, expose functions to add callbacks to the queue, and provide a way to "flush" (run) all queued callbacks:
function createQueue() {
const callbacks = []; // Private queue in closure
return {
add(fn) {
callbacks.push(fn);
},
flush() {
while (callbacks.length > 0) {
const fn = callbacks.shift();
fn();
}
}
};
}
const queue = createQueue();
queue.add(() => console.log('First'));
queue.add(() => console.log('Second'));
queue.flush(); // Logs: First, Second
Each closure instance maintains its own independent queue. The callbacks are safely hidden from external modification, and you control exactly when they execute.
Common Use Cases
- Batching updates: Collect multiple state changes, then apply them all at once
- Event coordination: Wait for multiple events to fire before proceeding
- Task scheduling: Defer work until the right moment
- Plugin systems: Let modules register hooks to run later
Key Takeaway: Callback queues use closures to privately store arrays of functions that can be executed in batch, giving you fine control over when and how multiple operations run.