I built a website that relies on frequently requesting and displaying data from a rest-api using fetch()
.
After I was done with the hardest part of the work I found that my site doesn't refresh like intended on my iPhone.
First I thought the reason is that Safari on iOS doesn't support setInterval()
which I used (which seemingly isn't the case).
On my search for an alternative to setInterval()
I soon came across "web workers". Using the above code I built my 'own' interval which works fine on every device I tested it on:
main script:
if (typeof(Worker) !== "undefined") {
let w = new Worker("webworker.js");
w.addEventListener("message", () => {
// my functionality here
w.postMessage("message");
});
w.postMessage("message");
}
webworker.js:
self.onmessage = (msg) => setTimeout(() => self.postMessage("message"), 5000);
Basically I'm fine with that code, but what I'd like to accomplish is to get rid of the dependence to another file (in this case "webworker.js").
I think an ideal solution would be to pass a function to the constructor of the Worker
:
let w = new Worker((msg) => {
self.onmessage = (msg) => {
setTimeout(() => self.postMessage("message"), 5000)
}
});
But as the constructor of the Worker
class requires an url, I don't see a way to get around this.
Does anyone know another class like Worker
that would do exactly that or another elegant way to achieve this?