Last active
May 31, 2024 21:38
-
-
Save dfkaye/3a9d6752301733fba81c740cf4fb68b2 to your computer and use it in GitHub Desktop.
visibility change and visibility state to drive web worker processing, pause and resume
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
// 30 May 2024 | |
// visibility change and visibility state to drive web worker processing, | |
// pause and resume. | |
// pretty sure I'd done this in 2022 or 2023. | |
// next version implements close and restart... | |
// https://gist.github.com/dfkaye/ee75271dd58e489d3a3ab9d209e51e02 | |
var source = ` | |
var count = 0; | |
var interval; | |
self.actions = { | |
init() { | |
interval = setInterval(function () { | |
count += 1; | |
postMessage({ action: "advanced", value: count }); | |
}, 1000); | |
}, | |
pause() { | |
clearInterval(interval); | |
postMessage({ action: "paused", value: count }); | |
}, | |
resume() { | |
actions.init(); | |
postMessage({ action: "resumed", value: count }); | |
} | |
}; | |
self.onmessage = function (request) { | |
var { action, value } = Object(request.data); | |
var fn = self.actions[action]; | |
typeof fn == "function" | |
? fn() | |
: console.error("no action for", action); | |
}; | |
actions.init(); | |
`; | |
var blob = new Blob([source], { type: "text/javascript" }); | |
var url = URL.createObjectURL(blob); | |
var worker = new Worker(url); | |
worker.onmessage = function (response) { | |
var { action, value } = Object(response.data); | |
console.log(action, value); | |
}; | |
document.onvisibilitychange = function (e) { | |
var { visibilityState } = e.target; | |
var action = visibilityState == 'hidden' | |
? 'pause' | |
: 'resume'; | |
worker.postMessage({ action }); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment