Cells evaluated sequentially when becoming visible

Say I have a notebook with many generator cells each yielding a canvas being generated step by step. Thanks to visibility(), we can have cells evaluated only when they’re visible, and it’s a huge benefit for user experience at page load.
But if you then scroll down and make many canvas-cells visible at a time, they will all begin to evaluate, and the user will see all the canvas being (very) slowly generated in parallel. I would rather like them to be sequentially (and thus individually more rapidly) evaluated.

My question is: is it possible to implement a mechanism forcing cells (only those that require it) to be evaluated sequentially when becoming visible ?

1 Like

Javascript is single-threaded, there’s no real parallel processing. Can you share an example?

If I understand you correctly, you want cells to evaluate when they become visible, but only one at a time in case more than one becomes visible at the same time. Here’s something which works:

The idea is to have each subsequent cell yield its starting frame in a loop until the previous cell has finished (detected by making each cell into a view and having its value change from false to true when it finishes). (I’d appreciate seeing cleaner solutions!)

EDIT: Just fixed some bugs, whoops!

While we’re on the topic of visibility, the “animate” function from @jrus’s notebook:

is useful if you want cells to stop animating when they are scrolled out of view.

If I understand you correctly, you want cells to evaluate when they become visible, but only one at a time in case more than one becomes visible at the same time.

Exactly.

Here’s something which works:

Very well done. The idea of a view whose dispatched value becomes true when the cell has finished is a good starting point, but in your example if forces cell2 to be aware of cell1, which is slightly inconvenient. I was rather thinking of a central “mutex” service cell…

While we’re on the topic of visibility , the “animate” function from @jrus’s notebook:

Woah, a lot to learn there…

1 Like

When a yield instruction pauses a generator, waiting for the next value to be pulled, it leaves the possibility for other portions of code to be executed. That’s not real parallelism of course, but that’s close enough for whoever is looking at this example:

When the 3 CPU-intensive cells are made visible at the same time, they will slowly progress in parallel. On the other hand, if you make them visible one at a time, they will execute rapidly, one at a time.

1 Like

Understood. Here’s a generic generator queue that should be easy to apply to other notebooks:

Edit: Just noticed that the queue might also need some way to restart, as resizing will cause problems. Not sure though if this should actually be handled in the queue.

3 Likes

Yep, that’s exactly the kind of solution I was looking for. Adapted successfully to the actual notebook. Thanks for your help !