JavaScript Explicit Resource Management: using and Symbol.dispose

Explicit resource management in JavaScript: using and Symbol.dispose

Cleanup code is easy to forget on the error path: an event listener that is never removed, an IntersectionObserver that keeps running, a lock that stays taken because an exception jumped over the release(). try/finally solves it, but nested finally blocks for three resources are hard to read. The using declaration calls a resource’s [Symbol.dispose]() method automatically when the block ends, normally or by an exception.

Problem: An admin screen opens a temporary MutationObserver, adds keyboard shortcuts and takes a Web Lock while a bulk operation runs. When the operation throws, the observer and the shortcuts stay active, and the next bulk run behaves strangely.

Solution: Wrap each resource in an object with a [Symbol.dispose]() method, declare it with using (or await using for async cleanup with [Symbol.asyncDispose]()), and let the block end clean up in reverse order. Use DisposableStack to collect cleanups that are created dynamically. Compile with Babel or TypeScript where browsers do not support the syntax yet.

A disposable listener

function haListen( target, type, handler, options ) {
    target.addEventListener( type, handler, options );
    return {
        [ Symbol.dispose ]() {
            target.removeEventListener( type, handler, options );
        },
    };
}

async function haRunBulk( items ) {
    using shortcuts = haListen( document, 'keydown', haOnBulkKey );
    using observer = haObserve( document.querySelector( '#ha-list' ) );

    for ( const item of items ) {
        await haProcess( item ); // if this throws, both are disposed
    }
}   // here: observer disposed first, then shortcuts

function haObserve( node ) {
    const mo = new MutationObserver( haOnListChange );
    mo.observe( node, { childList: true } );
    return { [ Symbol.dispose ]: () => mo.disconnect() };
}

using declares a constant whose value must have a [Symbol.dispose] method (or be null/undefined). When the enclosing block is left, by return, by the end of the block or by an exception, the dispose methods run in reverse declaration order. If a dispose method throws while another error is being propagated, both are kept in a SuppressedError.

Async cleanup

async function haWithLock( name, fn ) {
    await using lock = await haAcquire( name );
    return fn();
}

async function haAcquire( name ) {
    const { promise: released, resolve: release } = Promise.withResolvers();
    const { promise: acquired, resolve: onAcquired } = Promise.withResolvers();
    navigator.locks.request( name, () => {
        onAcquired();
        return released; // the lock is held until this promise resolves
    } );
    await acquired;
    return { [ Symbol.asyncDispose ]: async () => release() };
}

await using awaits [Symbol.asyncDispose]() at the end of the block. Here it releases a Web Lock, which prevents two tabs from running the same bulk operation at once, and the lock is released even when fn() throws. Promise.withResolvers(): ES2024 in WordPress scripts.

DisposableStack for dynamic resources

function haBindRows( rows ) {
    const stack = new DisposableStack();
    for ( const row of rows ) {
        stack.use( haListen( row, 'click', haOnRowClick ) );
    }
    return stack; // the caller disposes all at once: stack.dispose()
}

{
    using bindings = haBindRows( document.querySelectorAll( '.ha-row' ) );
    // ...
}

stack.use() registers a disposable, stack.defer( fn ) registers a plain cleanup function, and disposing the stack runs all of them in reverse order.

Support and build

The proposal is at Stage 3 and already shipped in browsers. using and Symbol.dispose work in Chrome and Edge 134 (March 2025) and Firefox 141 (July 2025); check Safari before shipping uncompiled code. With @wordpress/scripts, add Babel’s explicit resource management plugin; TypeScript supports the syntax since 5.2 and compiles it down. A file with using that is loaded uncompiled in an older browser is a syntax error for the whole file.

NOTE: For event listeners alone, an AbortController signal (addEventListener( type, fn, { signal } ), then controller.abort()) is the widely supported way to remove many listeners at once; using generalizes the idea to any resource.