Created
September 21, 2025 06:33
-
-
Save ardislu/da919532c9ca747d0d70db255334e6aa to your computer and use it in GitHub Desktop.
The minimal logic to block until garbage collection occurs in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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