JavaScript Academy · Lesson

Connection Lifecycle and Errors

Handle open, close, and error events.

Lesson 3 of 413 steps

Connection Lifecycle and Errors is a free JavaScript Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 4 lessons in total.

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.

Free to start

Learn JavaScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
59
Lessons
200

Frequently Asked Questions

Is the “Connection Lifecycle and Errors” lesson free?

Yes — any 3 lessons of the JavaScript Academy learning path, including “Connection Lifecycle and Errors”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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

  1. Opening a WebSocket Connection
  2. Sending and Receiving Messages
  3. Connection Lifecycle and Errors
  4. Reconnection Strategies
← Back to JavaScript Academy