Clean Markup

Deterministic Cleanup with JavaScript Explicit Resource Management

Deterministic Cleanup with JavaScript Explicit Resource Management

Managing the lifetime of external resources in JavaScript has historically required verbose try...finally blocks that are easy to nest improperly and even easier to forget during early returns or thrown exceptions. Whether holding an open file handle, an active database transaction, a Web Locks API acquisition, or a set of DOM event listeners, leaking cleanup paths creates subtle memory retention, dangling subscriptions, and resource contention under load.

The ECMAScript Explicit Resource Management specification—standardized in ES2025 and shipped across modern engines including V8, SpiderMonkey, and Node.js—introduces deterministic, scope-bound disposal directly into the language. With the using and await using declarations alongside Symbol.dispose, Symbol.asyncDispose, DisposableStack, and AsyncDisposableStack, JavaScript guarantees that resources are released in reverse declaration order the moment execution leaves their lexical block, even when exceptions occur or errors are chained via SuppressedError.

Example

function openTempLock(name) {
  console.log(`Acquired lock: ${name}`);
  return {
    name,
    [Symbol.dispose]() {
      console.log(`Released lock: ${name}`);
    }
  };
}

function runCriticalSection() {
  using lock = openTempLock('config-write');
  console.log(`Updating state under ${lock.name}`);
  // Lock is automatically released here when `runCriticalSection` exits
}

Implementation

/**
 * Disposable Event Listener & Timer Manager
 * Combines Explicit Resource Management (`using` / `await using`)
 * with DisposableStack for deterministic UI and I/O cleanup.
 */

class ScopedSubscriptions {
  #stack = new DisposableStack();

  /**
   * Registers a DOM event listener that removes itself on disposal.
   * @param {EventTarget} target
   * @param {string} eventType
   * @param {EventListenerOrEventListenerObject} handler
   * @param {AddEventListenerOptions} [options]
   */
  on(target, eventType, handler, options) {
    target.addEventListener(eventType, handler, options);
    this.#stack.defer(() => {
      target.removeEventListener(eventType, handler, options);
    });
    return this;
  }

  /**
   * Registers an AbortController tied to the lifetime of this scope.
   * @returns {AbortSignal}
   */
  createSignal() {
    const controller = new AbortController();
    this.#stack.defer(() => controller.abort('Scope disposed'));
    return controller.signal;
  }

  [Symbol.dispose]() {
    this.#stack.dispose();
  }
}

/**
 * Acquires an async resource handle with guaranteed asynchronous teardown.
 * @param {string} url
 */
async function openStreamSession(url) {
  const controller = new AbortController();
  const response = await fetch(url, { signal: controller.signal });

  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }

  const reader = response.body?.getReader() ?? null;

  return {
    reader,
    async [Symbol.asyncDispose]() {
      if (reader) {
        await reader.cancel().catch(() => {});
        reader.releaseLock();
      }
      controller.abort();
    }
  };
}

/**
 * Coordinates synchronous UI listeners and an asynchronous stream
 * inside a single deterministic cleanup boundary.
 * @param {HTMLElement} statusEl
 * @param {string} endpoint
 */
export async function syncLiveFeed(statusEl, endpoint) {
  using ui = new ScopedSubscriptions();
  const abortSignal = ui.createSignal();

  ui.on(window, 'offline', () => {
    statusEl.textContent = 'Connection paused';
  });

  await using session = await openStreamSession(endpoint);

  if (!session.reader || abortSignal.aborted) {
    return;
  }

  const decoder = new TextDecoder();
  while (true) {
    const { done, value } = await session.reader.read();
    if (done) break;
    statusEl.textContent = decoder.decode(value, { stream: true });
  }
}

Main Point: Explicit Resource Management binds resource disposal directly to lexical block scope through using and await using, eliminating manual try...finally boilerplate and preventing leaked handles or listeners on error paths.

Credits

Photo by Mads Schmidt Rasmussen on Unsplash

← Home