Skip to content

Instantly share code, notes, and snippets.

@nestarz
Last active December 23, 2022 02:57
Show Gist options
  • Save nestarz/c171ba996a78028d893fb6809ee93960 to your computer and use it in GitHub Desktop.
Save nestarz/c171ba996a78028d893fb6809ee93960 to your computer and use it in GitHub Desktop.
polling.ts
export default (fn, ms = 1000) => {
const connections = new Map();
let id: number | undefined;
const poll = async () => {
if (connections.size > 0)
await fn().then((results) =>
connections.forEach((conn) => conn(results))
);
if (connections.size > 0) id = setTimeout(poll, ms);
};
const setItem = async (cId, fn) => {
connections.set(cId, fn);
if (!id) await poll();
};
const deleteItem = (cId) => {
connections.delete(cId);
if (connections.size === 0) {
clearTimeout(id);
id = undefined;
}
};
return { setItem, deleteItem };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment