Practice & Assessment
Test your understanding of Browser WebSocket API
Multiple Choice Questions
5What does ws.binaryType = 'arraybuffer' change about received messages?
Why should jitter be added to WebSocket reconnection backoff delays?
Which close code should you use for an application-defined reason like 'auth token expired'?
What is the correct way to prevent reconnection when the user intentionally closes a WebSocket?
At what point is it safe to call ws.send() after creating a new WebSocket?
Coding Challenges
1Build a Reconnecting WebSocket Wrapper
Implement a createReconnectingWebSocket(url, options) factory function in plain JavaScript. It must: connect to the given URL, automatically reconnect on non-1000 close with exponential backoff (base 1s, max 30s, with random jitter up to 1s), expose onmessage, onopen, onclose callbacks, and a send(data) method that queues messages if the connection is not yet open and flushes the queue on reconnect. Input: a WebSocket URL string and an optional options object with maxRetries (default 10). Output: an object with send(), close(), and event handler properties. Estimated time: 25 minutes.
Mini Project
Browser WebSocket Debug Console
Build a single HTML page (no frameworks) with a WebSocket debug console. Features: a URL input field and Connect/Disconnect button that manages connection state; a message log area that displays each incoming frame with timestamp and direction arrow; a send area with a text input and Send button; a status bar showing current readyState as a color-coded badge (Connecting=yellow, Open=green, Closing=orange, Closed=red); automatic reconnection with exponential backoff and a visible retry counter; a heartbeat toggle that enables a 20-second ping/pong cycle and shows last pong latency. Implement all features using only vanilla JS and the browser WebSocket API.
