Created
February 20, 2024 16:40
-
-
Save sobstel/a689fdf901de40b537c0bc8a014d15e7 to your computer and use it in GitHub Desktop.
Background non-stopping setTimeout
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
const worker = null; | |
const start = (callback, delay) => { | |
const args = { foo: "abc" }; | |
worker = new Worker('/timeoutWorker.js'); | |
worker.onmessage = (event) => { | |
if (event.isTrusted && event.data === "timeout") { | |
callback(); | |
} | |
} | |
worker.postMessage({ action: 'start', delay: delay }); | |
} | |
stop() { | |
if (worker) { | |
worker.postMessage({ action: 'stop' }); | |
worker.terminate(); | |
} | |
} |
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
let timeoutId = null; | |
onmessage = (event) => { | |
const { action, delay, ...args } = event.data | |
if (action === 'start') { | |
timeoutId = setTimeout(() => postMessage("timeout"), delay || 0); | |
} | |
if (action === 'stop') { | |
clearTimeout(timeoutId); | |
} | |
} | |
onbeforeunload = (event) => { | |
clearTimeout(timeoutId); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment