Last active
December 23, 2022 02:57
-
-
Save nestarz/c171ba996a78028d893fb6809ee93960 to your computer and use it in GitHub Desktop.
polling.ts
This file contains hidden or 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
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