Running tight loops for instant updates

Neptyne has scheduled running cells to keep a spreadsheet up-to-date. But sometimes you need something with an even higher update frequency, like fetching data multiple times per second, showing the results of a long running calculation as they come in or you just want to use your spreadsheet as a canvas to display an animation.

In this how-to we’re going to show a spinning donut in a Neptyne spreadsheet based on this great https://vgel.me/posts/donut/ post. We’ll leave out the clever bit and focus on the main loop:

async def run():
    A1.caption = "Start" if A1.caption == "Stop" else "Stop"
    canvas = A1:AX35
    while True:
        if A1.caption == "Start":
            return
        for y, row in enumerate(canvas):
            for x, cell in enumerate(row):
                r, g, b = sample(x / len(row) * 2 - 0.85, y / len(canvas) * 1.7 - 0.85, speed=.25)
                cell.set_background_color(r, g, b)
        await nt.do_events(0.05)

We call this function from a button defined in cell A1:

=get_weather (A5,A6)
A
B
C
D
E
F
G
H
I
J
K
1
1

When you click the button, it will change its caption from Start to Stop and vice versa. In the main loop we check whether the button is Start and if so we exit the loop. The main loop itself uses the sample function to fetch the color for the “pixel” at x and y and then calls

set_background color on the relevant cell. Note the enumerate patterns as a good way to loop through cells while also getting their index.

The final statement is a call to do_events which allows the system to process events, like the clicking of the button. If we didn't do this, we would not be able to stop the loop.