Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function createQueue() {
let queue = [];
let i = 0;
let len = 0;
return [
(fn) => (queue[len++] = fn),
() => {
try {
for (; i < len; i++) {
const fn = queue[i];
// release memory
queue[i] = undefined;
fn();
}
} finally {
if (i < len) {
i++;
} else {
len = i = 0; // completed
}
}
},
];
}
const [enqueue, flush] = createQueue();
enqueue(() => console.log("A"));
enqueue(() => console.log("B"));
enqueue(() => {
throw Error("foo");
});
enqueue(() => console.log("C"));
enqueue(() => console.log("D"));
while (true) {
try {
flush();
break;
} catch (e) {
console.log(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment