This clock freezes in embarrassment when it is viewed.
Setting Up the Server
These are the parts of the node.js server side that keep things running:
- DigitalOcean droplet
- I caved and used a paid account
- Express router
- A way to route url hits to specific files
- A way to send realtime updates to connected clients
- An interval timer
- A way to do something at regular intervals (more below)
Logically the shy clock is very simple. You need to keep track of what the clock thinks time is, which I’ve done in a variable called ‘visibleTime’. visibleTime is a Date.now() timestamp taken when the server starts, and updated according to the below system.
At regular intervals (for instance every half second):
- Check whether there are any active connections.
- If there are any active connections:
- Do Not Update Time
- Increment visibleTime partially towards the actual current time (Date.now());
Whenever a user connects, send them the current visibleTime.
Since the clock will not move while the user is viewing it, the above needs only happen once.
The above algorithm results in a clock that freezes when any user is viewing it. Once everyone has disconnected, the clock slowly catches up to real time.