Skip to content

Instantly share code, notes, and snippets.

@ardislu
Created September 21, 2025 06:33
Show Gist options
  • Select an option

  • Save ardislu/da919532c9ca747d0d70db255334e6aa to your computer and use it in GitHub Desktop.

Select an option

Save ardislu/da919532c9ca747d0d70db255334e6aa to your computer and use it in GitHub Desktop.
The minimal logic to block until garbage collection occurs in JavaScript.
/**
* Helper function that will block until garbage collection is performed.
*
* **WARNING:** By design, JavaScript garbage collection is unpredictable and may never happen (i.e., this
* function may never resolve). Use this function with caution.
*/
async function garbageCollection() {
const { promise, resolve } = Promise.withResolvers();
const registry = new FinalizationRegistry(resolve);
(() => registry.register({}, ''))();
// Theoretically, you can just do `await promise;` However, in testing,
// `promise` never resolves. So, the infinite loop is required.
let collected = false;
promise.then(() => collected = true);
while (!collected) { await new Promise(r => setTimeout(r, 0)); }
}
// Usage example:
// await garbageCollection().then(() => console.log('Garbage collected!'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment