Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Last active June 13, 2025 09:11
Show Gist options
  • Save aliakakis/6c8d59310350a60b0342d4b61fae3051 to your computer and use it in GitHub Desktop.
Save aliakakis/6c8d59310350a60b0342d4b61fae3051 to your computer and use it in GitHub Desktop.
Event Queue
/*
Example
const q = EventQueue({}); You can also use the 'new' keyword
q.enQueue(async () => {
// [CODE HERE]
});
OR
q.enQueue([
async () => {
// [CODE HERE]
},
async () => {
// [CODE HERE]
}
]);
*/
export type EventQueue = {
showLogs: boolean;
};
export type EventQueueTask = () => void;
export const EventQueue = ({ showLogs = false }: EventQueue) => {
const tasks: EventQueueTask[] = [];
let isLocked = false;
async function enQueue(task: EventQueueTask | EventQueueTask[]) {
if (task instanceof Array) {
tasks.unshift(...task.reverse());
} else {
tasks.unshift(task);
}
async function exec(taskFn: EventQueueTask) {
try {
await new Promise((resolve) => {
taskFn();
resolve(taskFn);
});
} catch (error) {
console.log("TASK ERROR:", error);
} finally {
queueMicrotask(() => {
isLocked = false;
});
}
}
while (tasks.length && !isLocked) {
if (showLogs) console.log("TASKS ARRAY:", tasks);
isLocked = true;
let currentTaskRunning = tasks.pop();
if (typeof currentTaskRunning !== "function") {
console.error(
`Did you forget to pass a function? Type is ${typeof currentTaskRunning} with value ${currentTaskRunning}`,
);
} else {
await exec(currentTaskRunning);
}
}
}
return {
enQueue,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment