Skip to content

Lifecycle & Cleanup

The Course
•
16 min study

Leaving a view is a state change too

A request can settle after its UI is gone. A timer can retain a callback. A repeated setup can register the same action several times. These are lifecycle problems: something starts, but nothing owns when it ends.

A controller can expose dispose(), mark itself unavailable, invalidate outstanding tokens, and abort active work. Its completion paths check the disposed flag before rendering. After disposal, calling load again should either do nothing or fail explicitly according to the contract. Our project chooses no further work.

DOM listeners can be grouped using an AbortSignal: element.addEventListener("click", handler, { signal }). Aborting that signal removes the registered listeners. This is separate from the signal for a particular request; one owns the UI subscription lifetime, the other owns one attempt. The { once: true } option removes a listener after its first invocation.

Use clearTimeout for a timer you no longer need. The demo below gives one owner two listeners and a timer, then ends all three with one dispose().

Release real resources

EventTarget and CustomEvent work in console JavaScript as well as pages, so this demo needs no DOM. createAutosave saves 10 ms after an edit. The view is disposed while a save is still scheduled. Predict what was saved.

One owner, two listeners and a timer JavaScript
async function main() {
  function createAutosave(target, save) {
    const owner = new AbortController();
    let timer = null;

    function onEdit(event) {
      clearTimeout(timer);
      timer = setTimeout(() => save(event.detail), 10);
    }

    // Both listeners share one signal, so one abort removes both.
    target.addEventListener("edit", onEdit, { signal: owner.signal });
    target.addEventListener("discard", () => clearTimeout(timer), { signal: owner.signal });

    return {
      dispose() {
        owner.abort();
        clearTimeout(timer);
      }
    };
  }

  const editor = new EventTarget();
  const saved = [];
  const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
  const view = createAutosave(editor, text => saved.push(text));

  editor.dispatchEvent(new CustomEvent("edit", { detail: "draft 1" }));
  await pause(30);
  editor.dispatchEvent(new CustomEvent("edit", { detail: "draft 2" }));
  view.dispose(); // leave the view while a save is still scheduled
  editor.dispatchEvent(new CustomEvent("edit", { detail: "draft 3" }));
  await pause(30);

  console.log(saved.join(", "));
}

main();
Check your prediction
Text
draft 1

"draft 2" was scheduled but clearTimeout cancelled it during dispose(). "draft 3" was never scheduled, because owner.abort() removed both listeners that shared its signal. Remove clearTimeout(timer) from dispose and "draft 2" is saved after the view is gone. Remove owner.abort() and "draft 3" is saved too.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
function createView() {
  let disposed = false;
  const messages = [];

  return {
    show(text) {
      if (!disposed) {
        messages.push(text);
      }
    },
    dispose() {
      disposed = true;
    },
    snapshot() {
      return [...messages];
    }
  };
}

const view = createView();

view.show("Ready");
view.dispose();
view.show("Too late");
console.log(view.snapshot().join(", "));
Check your prediction
Text
Ready

A copied snapshot avoids letting the caller mutate the internal array.

Dispose prevents future effects, not just future clicks

A view can disappear while work is pending. Removing an event listener stops future events but does not erase callbacks already waiting on a promise. The lifetime guard must be checked when the result is about to be applied.

Cleanup should be safe to call twice, because callers may share responsibility for ending a lifetime. Choose who owns timers, listeners and pending operations, and make each cleanup path explicit. Do not use a disposed flag as a substitute for releasing resources that can actually be released.

Dispose prevents future effects, not just future clicks: trace JavaScript
async function main() {
  let release;
  const pending = new Promise(resolve => {
    release = resolve;
  });
  let disposed = false;
  let visible = "before";
  const work = pending.then(value => {
    if (!disposed) {
      visible = value;
    }
  });

  disposed = true;
  release("too late");
  await work;
  console.log(visible);
}

main();
Check your prediction
Text
before

The guard runs after the pending value is available. Checking only before starting the work would not protect this schedule.

Dispose prevents future effects, not just future clicks: contrast JavaScript
function createOwner() {
  let disposed = false;
  let cleanups = 0;

  return {
    dispose() {
      if (!disposed) {
        disposed = true;
        cleanups++;
      }
    },
    count() {
      return cleanups;
    }
  };
}

const owner = createOwner();

owner.dispose();
owner.dispose();
console.log(owner.count());
Check your prediction
Text
1

An idempotent operation makes repeated cleanup harmless. The counter stands in for releasing an owned resource exactly once, not just setting an unrelated boolean.

Try the rule on new inputs

Hold a request, dispose the owner, then resolve and reject controlled attempts. Neither should update visible data. List which resources need removal as well as guards, and who is responsible for calling cleanup.

Build it yourself

Exercise

A live view that owns its requests

The demo above owned listeners and a timer. This view also owns requests. Write createLiveView(target, load, render). Each "refresh" event (the query is event.detail) calls load(query, signal) and renders the result. Only the newest refresh may render: starting a refresh aborts the previous request's signal, and a result that arrives for an aborted request is ignored, because, like many real APIs, this load ignores its signal and answers anyway. dispose() removes the listener, aborts the request in flight, and returns true the first time and false after that. The test settles each load itself with a deferred promise and prints:

Text
a aborted when b started: true
rendered: result b
first dispose: true
c aborted by dispose: true
rendered after dispose: result b
loads started: 3
second dispose: false
Your working space JavaScript
async function main() {
  function createLiveView(target, load, render) {
    // First draft: renders every result and never cleans up.
    target.addEventListener("refresh", async event => {
      const result = await load(event.detail, new AbortController().signal);
      render(result);
    });
    return {
      dispose() {
        return true;
      }
    };
  }

  // ---- test: each load waits until the test settles it ----
  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }
  const tick = () => new Promise(resolve => setTimeout(resolve, 0));
  const refresh = (target, query) => target.dispatchEvent(new CustomEvent("refresh", { detail: query }));

  const target = new EventTarget();
  const loads = [];
  const screen = [];
  const view = createLiveView(
    target,
    (query, signal) => {
      const gate = deferred();
      loads.push({ query, signal, gate });
      return gate.promise; // this load ignores its signal, like many real APIs
    },
    result => screen.push(result)
  );

  refresh(target, "a");
  refresh(target, "b");
  console.log(`a aborted when b started: ${loads[0].signal.aborted}`);
  loads[0].gate.resolve("result a"); // a late answer for the old query
  loads[1].gate.resolve("result b");
  await tick();
  console.log(`rendered: ${screen.join(", ")}`);

  refresh(target, "c");
  console.log(`first dispose: ${view.dispose()}`);
  console.log(`c aborted by dispose: ${loads[2].signal.aborted}`);
  loads[2].gate.resolve("result c");
  refresh(target, "d");
  await tick();
  console.log(`rendered after dispose: ${screen.join(", ")}`);
  console.log(`loads started: ${loads.length}`);
  console.log(`second dispose: ${view.dispose()}`);
}

main();
Hint 1: the idea

Two different lifetimes need two different owners. One AbortController lives as long as the view and owns the listener. A new AbortController per refresh lives as long as that one request. A request's own signal is also the simplest way to ask, after await, "am I still the request this view wants?"

Hint 2: a first step

Run the starter and find the two wrong lines: result a is rendered although a was replaced, and result c appears after dispose. Fix the first: give each refresh its own controller, keep the current one in a variable, abort the previous one when a new refresh starts, and check the signal after the await. Then move to dispose.

Show one solution
JavaScript
async function main() {
  function createLiveView(target, load, render) {
    const owner = new AbortController(); // owns the listener
    let active = null; // owns the request in flight
    let disposed = false;

    async function refresh(event) {
      active?.abort();
      const request = new AbortController();
      active = request;
      try {
        const result = await load(event.detail, request.signal);
        if (!request.signal.aborted) render(result);
      } catch {
        // an aborted or failed refresh renders nothing here
      }
    }

    target.addEventListener("refresh", refresh, { signal: owner.signal });

    return {
      dispose() {
        if (disposed) return false;
        disposed = true;
        owner.abort();
        active?.abort();
        return true;
      }
    };
  }

  // ---- test: each load waits until the test settles it ----
  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }
  const tick = () => new Promise(resolve => setTimeout(resolve, 0));
  const refresh = (target, query) => target.dispatchEvent(new CustomEvent("refresh", { detail: query }));

  const target = new EventTarget();
  const loads = [];
  const screen = [];
  const view = createLiveView(
    target,
    (query, signal) => {
      const gate = deferred();
      loads.push({ query, signal, gate });
      return gate.promise; // this load ignores its signal, like many real APIs
    },
    result => screen.push(result)
  );

  refresh(target, "a");
  refresh(target, "b");
  console.log(`a aborted when b started: ${loads[0].signal.aborted}`);
  loads[0].gate.resolve("result a"); // a late answer for the old query
  loads[1].gate.resolve("result b");
  await tick();
  console.log(`rendered: ${screen.join(", ")}`);

  refresh(target, "c");
  console.log(`first dispose: ${view.dispose()}`);
  console.log(`c aborted by dispose: ${loads[2].signal.aborted}`);
  loads[2].gate.resolve("result c");
  refresh(target, "d");
  await tick();
  console.log(`rendered after dispose: ${screen.join(", ")}`);
  console.log(`loads started: ${loads.length}`);
  console.log(`second dispose: ${view.dispose()}`);
}

main();
Text
a aborted when b started: true
rendered: result b
first dispose: true
c aborted by dispose: true
rendered after dispose: result b
loads started: 3
second dispose: false

Each refresh creates its own AbortController and stores it in active, so starting b can abort a's signal. That abort cannot stop this load, which answers anyway, but request.signal.aborted is checked after the await, so result a is dropped. The check uses this request's signal rather than active, because by the time a resumes, active already points to b. dispose ends both lifetimes: owner.abort() removes the listener, so the refresh for d starts no load (3 loads in total), and active?.abort() marks c as unwanted, so its late result is never rendered. The disposed flag makes a second dispose() a harmless false. Removing active?.abort() from dispose would let result c reach a view that no longer exists.

Explain before moving on

Why should listeners and request attempts have different lifetimes? What should a pending rejection do after disposal?

Going further

Pages that are kept for later. For page-level code, pagehide reports leaving the page. When event.persisted is true, the browser is keeping the page in its back/forward cache so it can resume later. The reading-queue demo keeps its controller in that case, because disposing it would leave a restored page with dead controls; it cleans up only when the page is not being retained. Do not attach that conditional cleanup with once: true, because an earlier cached visit could consume the only listener. In a component system, use that system's lifecycle boundary instead.

MDN explains pagehide and its persisted flag. The important distinction for this demo is pausing a cached page versus discarding it; you do not need to implement a general page cache.

Was this article helpful?

Your response is saved on this device.