Created
May 31, 2024 21:37
-
-
Save dfkaye/ee75271dd58e489d3a3ab9d209e51e02 to your computer and use it in GitHub Desktop.
visibility change and visibility state to drive web worker processing, closeand restart.
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
// 31 May 2024 | |
// visibility change and visibility state to drive web worker processing, close | |
// and restart. | |
// previous version, pause and resume, at | |
// https://gist.github.com/dfkaye/3a9d6752301733fba81c740cf4fb68b2 | |
var source = ` | |
var count = 0; | |
var interval; | |
self.actions = { | |
init() { | |
interval = setInterval(function () { | |
count += 1; | |
postMessage({ action: "advanced", value: count }); | |
}, 1000); | |
}, | |
stop() { | |
clearInterval(interval); | |
self.close(); | |
// this post will deliver even though we've requested the current worker | |
// be terminated (closed). | |
postMessage({ action: "stopped", value: count }); | |
}, | |
start() { | |
actions.init(); | |
postMessage({ action: "started", 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.start(); | |
`; | |
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); | |
// }; | |
~(function restart() { | |
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; | |
if (visibilityState == 'hidden') { | |
worker.postMessage({ action: "stop" }); | |
} | |
else { | |
console.log("should restart"); | |
// use a timeout to make the start log more obvious | |
setTimeout(restart, 1000); | |
} | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment