C.W.K.
Stream
Lesson 07 of 08 · published

Live Presence & Cursors

~11 min · app, presence, cursors

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Cursor positions throttled, not raw

Browser mousemove fires hundreds of times per second. Sending each one over WebSocket would saturate the connection and waste server resources. Throttle to 20-30 updates per second; the human eye does not need more for smooth cursor rendering, especially with CSS transitions to interpolate between points.

Presence is just a special-case message

"User X is online" is one message; "user X is offline" is another; "user X has cursor at (100,200) in document Y" is another. There is no special "presence" protocol — it is just typed messages your application interprets. Figma calls them presence; Slack calls them user.status; the wire shape is the same.

Code

Client: throttle cursor + render others·javascript
let lastSent = 0;
const THROTTLE_MS = 50; // 20 Hz

document.addEventListener('mousemove', (e) => {
  const now = Date.now();
  if (now - lastSent < THROTTLE_MS) return;
  lastSent = now;
  ws.send(JSON.stringify({
    type: 'presence.cursor',
    data: { x: e.clientX, y: e.clientY },
  }));
});

const cursors = new Map(); // userId -> element
ws.on('presence.cursor', ({ user_id, color, x, y }) => {
  let el = cursors.get(user_id);
  if (!el) {
    el = document.createElement('div');
    el.className = 'live-cursor';
    el.style.background = color;
    el.style.position = 'fixed';
    el.style.transition = 'transform 50ms linear';
    document.body.appendChild(el);
    cursors.set(user_id, el);
  }
  el.style.transform = `translate(${x}px, ${y}px)`;
});

External links

Exercise

Build live cursors with two browser tabs as different users. Throttle to 20Hz. Add CSS transitions. Move your mouse; observe the other tab's cursor following with sub-50ms latency. Now drop the throttle to 5Hz; with transitions still on, can you tell the difference visually?

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.