MessageChannel

Lesson 7 · ~8 minutes · teardown this time

Close the extra pipe

The extra pair is a conversation. When it is done, close() the handles you hold. The worker stays.

Lesson 2 cut a same-page pair. The design default on an extra worker (or iframe) pipe is the same: close() both ends you still own. One close() disentangles the twins — later posts find no target. Closing the object you hold is what lets it be collected. Do not wait for garbage collection, and do not terminate() the worker just to drop a second stream. (HTML §9.4.5, §10.1.2.6 — the crypto example calls port.close() when the conversation is finished)

port1.close();
worker.postMessage("done");   // tell the other context to close port2
worker.postMessage("job");    // implicit — still alive

A transferred port nobody listens on is silent: its queue is born disabled, so posts sit and never dispatch. Either onmessage / start(), or close() it. Leaving it idle is the leak. The spec can fire a close event on the other end when this end disentangles. That event is newer than close() — treat it as a bonus, not the teardown you design around.

Feel the teardown

Transfer an extra port, talk, close both extra handles, send again (it should drop), then ping implicit. The worker should still answer on the implicit pipe.

The lab needs JavaScript in this page.

Check

The extra worker conversation is done. The worker should keep running. What do you do?

Why close the extra handle in both contexts, not only on the parent?

You closed the extra pipe, then call worker.postMessage("job"). What happens?

You transferred port2 into a worker and nobody calls start() or sets onmessage. What happens to posts?

How do you detect that the other extra end called close(), as a design default?

You already close()d the extra port1. You postMessage on that same object. What happens?

Primary source

Read HTML Living Standard §9.4.5 (close ports you hold; do not wait for GC). Then the finished-conversation port.close() in §10.1.2.6.

Ask the teacher

If “why isn’t closing the extra pipe just worker.terminate()?” is still mushy — ask. Next: lesson 8 — mixed choose/reject and teardown from memory. Pocket cards: entangled ports, port API, transfer, choose.