Keep a notebook running in background?

I think (but am not certain) that when I have a notebook running a generator and then move to a different tab, that the generator is throttled… at least in some cases.

Is that true? Maybe after some period of time?

If yes, is there anything I can set to permit it to keep running normally?

One example is a cell with something like this running:

  while (true) {
    let end = new Date()
    let start = new Date(new Date() - 3 * 60 * 1000)
    let url = `${blah}`
    let params = [
      `start=${start.toISOString()}`,
      `end=${end.toISOString()}`,
    ]
    let new_data = await ((await fetch(`${url}&${params.join("&")}`)).json())
    yield new_data;
    await Promises.delay(1000);
  }
}
1 Like

I believe that’s true, yes. More generally, I think this is true for Javascript programs - not just for Observable programs. I get around this in Firefox by letting the notebook run in it’s own window, rather than a separate tab.

Another effect is that Observable consumes values from generators like this via requestAnimationFrame. That will run at most as fast as your screen refreshes (60hz for most systems), and is generally slowed down even more than normal JS in background tabs. It may be helpful to avoid generators if you want to get slowed down less in background tabs, and use something like a custom viewof cell that can emit values more frequently.

It annoys me too, please upvote issue Runtime stops executing when switching tabs · Issue #458 · observablehq/feedback · GitHub

It’s not a general JS issue, it’s the way the reactive runtime is driven by requestAnimationFrame, it could be changed, potentially.

2 Likes

Interesting. The reason I surmised it to be a general JS issue is because I’ve seen it before in many Javascript programs I’ve written long before I ever used Observable. I guess it’s something I’m doing in my own code. :confused:

1 Like

I sat on that issue for about 6 months too because I was not sure if it was intrinsic to JS or not. It’s not but some people like it the way it is e.g. jrus, so it’s definitely worth speaking up if you would prefer observable to work when backgrounded. See the issue thread for details.

To expand on my comment about not using generators to avoid the request animation frame slowdown, I made this notebook that implements a changing value using both a generator style and a viewof style. It’s definitely not a convenient as the built in generator support, but it’s nice to have the alternative.

1 Like

Oh that’s interesting, but the bigger issue is that the whole runtime that allows a change in one cell to notify other cells is also scheduled by requestAnimationFrame. So while you might get a cell to update via other means, I don’t think you can signal that change to other cells and build a program out of it, with no work around.