Flip clock from a time element

The clock is one <time> element drawn by a canvas. A timer changes its text once a second. Each change fires paint, and the canvas flips the digits that differ from a snapshot of the old text to the new text. The page has no frame loop: the frames of a flip come from a CSS animation on the element. Change the time zone to flip most of the digits at once.

 

Show the code a timer, a snapshot and a CSS animation; no requestAnimationFrame
  1. The clock. A <time> element with the digits and a date line.
  2. The styles. A registered property --flip, and a border colour computed from it.
  3. Once a second. Take a snapshot, change the text, start the animation.
  4. On paint. Read --flip and draw each changed digit part way between the snapshot and the element.
  5. One flap part way through a flip.

How it works

A setTimeout() aimed at the start of each second formats the time and compares it with the element's text. When they differ it does three things: it calls captureElementImage() to keep a picture of the element as it is, it sets the new text and the datetime attribute, and it starts a Web Animation that runs the registered custom property --flip from 0 to 1 in 520 ms.

The text change fires paint. The animation fires paint on every frame while it runs, because the element's top border has a colour computed from --flip. The paint handler reads --flip with getComputedStyle() and uses it as the progress of the flip. For each digit that changed, the old face is a piece of the snapshot and the new face is a piece of the live element. When the animation ends the paint events stop, and nothing runs until the next second.

The line under the controls counts the paint events and the calls the page made. requestPaint() is called when the canvas changes size and when it scrolls into the window, and not for the clock.

Live checks

These run on their own fixtures in the corner of the window, after a tap on the button.

Findings