Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Preventing JavaScript from Stopping in Safari When It Goes into the Background

From a mail app or similar, when opening a webpage in Safari as an external browser, JavaScript on the webpage stops running if Safari goes into the background. Is there a way to prevent this from happening?

Sample code for the counter:

  • Behavior: Upon returning from the background, the counter continues for about 7-8 seconds but does not progress further.
  • For example, if Safari is kept in the background for about 20 seconds and then brought back, the counter stops at around 7-8 seconds and only resumes counting after returning to the foreground.
  • Expectation: The counter should continue running even if Safari goes into the background.

SampleCode

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
      .counter {
          display: flex;
          font-size: 70px;
          justify-content: center;
          align-items: center;
          margin-top: 50%;
      }
  </style>
</head>
<body>
<p class="counter"></p>
</body>
<script>
    let count = 0;
    setInterval(() => {
        count++;
        document.querySelector('.counter').textContent = count;
    }, 1000);
</script>
</html>

Is this on iOS or MacOS?

If you are trying to keep running UI when the app itself is in the background, you cannot control this.

You can use service workers or background scripts to perform tasks on MacOS.

On iOS it is very intentional to prevent this kind of behavior.

You can also try running a counter from a reference date so the correct countdown time will show without worrying about animating in the background.

Hello! I've run into this issue too! I'm not sure it's possible to force your JavaScript to run while the app is in the background, but you can detect if it's no longer visible or in the background, which is how I addressed the issue on one of my websites!

var inter = setInterval(() => {
  if ((document.visibilityState === 'visible')) {
    //run code or call function here.
    clearInterval(inter)
  }
}, 1000);

I hope this helps.

The operating environment is iOS. So, it is intentional for the operation to stop in the background on iOS.

@Braden_Tiernan

I first learned that this can be detected! Thank you!

Preventing JavaScript from Stopping in Safari When It Goes into the Background
 
 
Q