Odd side effect with now vs Date.now()

I noticed some of Mike B’s sketches (the moving circles were hugely useful by the way) using what appears to be a built-in “now” variable as opposed to the more typical Date.now(), so I tried it. It has an odd side effect.

Check out this sketch:


Here I’m using a trick of repainting the screen with a translucent color to produce trails.

If you replace my use of Date.now() with now, you’ll see the trails disappear. It’s like it causes the canvas to get cleared each frame of animation. Is the use of ‘now’ activating some kind of alternate animation model that clears the canvas? Or is it causing the animation block to get reset?

now is part of the Observable standard library — you can find its definition here:

As you can see, it’s just a generator function that yields Date.now().

In your notebook, this makes it an external value that changes whenever you call it (in the notebook, typically 60fps). If you have a cell that references it, that cell will be re-evaluated at the same rate.

The “animation model” hasn’t changed at all. It’s just that cells that refer to other cells are re-evaluated whenever any of their inputs change.

For more, see: https://beta.observablehq.com/@mbostock/five-minute-introduction … particularly the bits about re-evaluation, generators, and async iteration.

1 Like

OK, I got it. Sketch is much improved now - thanks!