Skip to content

Instantly share code, notes, and snippets.

@westy92
Last active July 25, 2019 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westy92/46e4af00992f2157a98bb7ef736a00a4 to your computer and use it in GitHub Desktop.
Save westy92/46e4af00992f2157a98bb7ef736a00a4 to your computer and use it in GitHub Desktop.
Queued Callback
/*
Sometimes you need to queue things up before a callback is available. This solves that issue.
Push any item(s) to an array.
Once you want to start consuming these items, pass the array and a callback to QueuedCallback().
QueuedCallback will overload array.push as your callback and then cycle through any queued up items.
Continue to push items to that array and they will be forwarded directly to your callback. The array will remain empty.
Compatible with all browsers and IE 5.5+.
*/
var QueuedCallback = function(arr, callback) {
arr.push = callback;
while (arr.length) callback(arr.shift());
};
var things = [];
things.push('first item before handler');
things.push('second item before handler');
console.log(things);
QueuedCallback(things, function(e) {
console.log('handling item: ' + e);
});
console.log(things);
things.push('first item after handler');
things.push('second item after handler');
console.log(things);
/*
Console output:
["first item before handler", "second item before handler"]
handling item: first item before handler
handling item: second item before handler
[]
handling item: first item after handler
handling item: second item after handler
[]
*/
@westy92
Copy link
Author

westy92 commented Dec 7, 2016

Reserved for future comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment