Last active
July 25, 2019 21:56
-
-
Save westy92/46e4af00992f2157a98bb7ef736a00a4 to your computer and use it in GitHub Desktop.
Queued Callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 | |
[] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reserved for future comments.