0

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?

Hombre83
  • 1
  • 1
  • *I found that devices like the iPhone do not support setInterval()* - this is not true, every browser supports `setInterval` – Konrad Mar 01 '23 at 14:31
  • Ok, that's weird as my site works on a Mac but not on the iPhone. Maybe there's something else wrong, but definitely there has to be a difference between how the mobile browser is interpreting the code vs. the desktop browser – Hombre83 Mar 01 '23 at 14:34
  • Maybe you should ask about the failing interval instead? According to [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/setInterval#browser_compatibility) setInterval is widely supported. – Teemu Mar 01 '23 at 14:34
  • Strange... but still it would be interesting if it's possible somehow to not relate to an external source when using "Worker". – Hombre83 Mar 01 '23 at 14:37
  • Google "how to debug iphone safari on mac" so you can check what causes the problem – Konrad Mar 01 '23 at 14:41

0 Answers0