A queue removes items in the same order they are added. In browser JavaScript, it can coordinate asynchronous work that would otherwise finish out of order, such as DOM updates triggered by network requests. section 16.3 section 16.7
The reusable JavaScript queue follows a small sequence:
- Encapsulate the item array and working flag inside Queue(worker), hiding its state from callers. section 16.4
- Return an operation that adds data and an optional completion callback to the queue. section 16.6
- Start the next item only when no worker is active, then mark the queue as working. section 16.4
- Let the worker call done when its asynchronous task finishes; done clears the flag and starts the next item. section 16.6
Serializing shopping-cart totals
Each click adds a cart state to update_total_queue. The worker calculates its total through AJAX, updates the DOM, and signals completion. Later requests cannot overwrite earlier updates because only one queued task runs at a time. section 16.4 section 16.7
function Queue() { #1
var queue_items = [];
var working = false; #2
function runNext() {
if(working)
return;
if(queue_items.length === 0)
return;
working = true;
var cart = queue_items.shift();
calc_cart_total(cart, function(total) {
update_total_dom(total);
working = false;
runNext();
});
}
return function(cart) { #3
queue_items.push(cart);
setTimeout(runNext, 0);
};
}
var update_total_queue = Queue(); #4
Inspect the compact Queue implementation, including its private state, worker, completion handoff, and returned enqueue operation. section 16.4
A normal queue processes every pending task, which may waste time when only the newest result matters. A dropping queue limits pending items and discards older work that would soon be overwritten. section 16.9






















