Skip to content

Instantly share code, notes, and snippets.

@sobstel
Created February 20, 2024 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sobstel/a689fdf901de40b537c0bc8a014d15e7 to your computer and use it in GitHub Desktop.
Save sobstel/a689fdf901de40b537c0bc8a014d15e7 to your computer and use it in GitHub Desktop.
Background non-stopping setTimeout
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();
}
}
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