Connection Lifecycle and Errors
Handle open, close, and error events.
Connection Lifecycle and Errors is a free JavaScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Full Lifecycle
A socket moves through CONNECTING → OPEN → CLOSING → CLOSED. Four events map to these transitions: open, message, error, and close.
The onclose Event
onclose fires when the connection ends, cleanly or not. The event carries code, reason, and wasClean.
socket.onclose = (event) => {
console.log("Closed", event.code, event.reason, event.wasClean);
};Close Codes
Standard codes include 1000 (normal), 1001 (going away), 1006 (abnormal, no close frame), and 1011 (server error). Codes 4000–4999 are app-defined.
socket.onclose = (e) => {
if (e.code === 1000) console.log("normal close");
else console.log("unexpected", e.code);
};Closing Deliberately
socket.close(code, reason) initiates a graceful shutdown. Use 1000 for a normal close; the reason string must be under 123 bytes.
socket.close(1000, "user logged out");The onerror Event
onerror fires on failures. For security, the error event is intentionally sparse — it carries no detailed reason. A close event almost always follows.
socket.onerror = (event) => {
console.log("Socket error — a close will follow");
};Distinguishing Clean vs Abnormal
event.wasClean is true only when both sides exchanged close frames. A dropped network gives wasClean: false and code 1006.
socket.onclose = (e) => {
if (!e.wasClean) console.log("Connection dropped unexpectedly");
};Cleaning Up Resources
On close, clear timers (heartbeats), reject pending requests, and update UI state so the app reflects the disconnection.
socket.onclose = () => {
clearInterval(heartbeatTimer);
pending.forEach((reject) => reject(new Error("disconnected")));
pending.clear();
};Removing Listeners
If you attached handlers with addEventListener, remove them on close to avoid leaks, especially when recreating sockets.
function cleanup() {
socket.removeEventListener("message", onMessage);
socket.removeEventListener("close", onClose);
}readyState During Shutdown
Between calling close() and the onclose event, readyState is CLOSING (2). Sending in this window is ignored.
socket.close();
console.log(socket.readyState); // 2 (CLOSING)Idle Timeouts from Servers
Servers and proxies often close idle connections after 30–60 seconds. Heartbeats keep the connection active and let you detect drops promptly.
Detecting a Dead Connection
Combine heartbeats with a watchdog: if no pong arrives within a window, treat the socket as dead and close it to trigger reconnection.
let pongTimer;
function ping() {
socket.send(JSON.stringify({ type: "ping" }));
pongTimer = setTimeout(() => socket.close(4000, "no pong"), 5000);
}
socket.onmessage = (e) => {
if (JSON.parse(e.data).type === "pong") clearTimeout(pongTimer);
};Quick Check
Test lifecycle handling.
Recap: Lifecycle and Errors
You handled onclose with its code/reason/wasClean, learned standard close codes, closed deliberately, dealt with the sparse onerror, cleaned up timers and listeners, and built a heartbeat watchdog. Next: reconnection strategies.
Frequently asked questions
Is the “Connection Lifecycle and Errors” lesson free?
Yes — the full text of “Connection Lifecycle and Errors” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Connection Lifecycle and Errors”?
Handle open, close, and error events. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Connection Lifecycle and Errors” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Opening a WebSocket Connection
- Sending and Receiving Messages
- Connection Lifecycle and Errors
- Reconnection Strategies