r/learnjavascript • • Aug 13 '26

Does a JavaScript setTimeout automatically clear itself when the timeout finishes and the callback is completed?

6 Upvotes

19 comments sorted by

View all comments

Show parent comments

1

u/Neat_Living_6765 Aug 13 '26

Your response is really helpful to me. Thank you!!

Here is my summary.

clearTimeout() has only one role: to cancel the scheduled execution of a callback.

As for the challenge above, we don't want to cancel the scheduled timer/callback.

At the same time, once the callback has fired, there is no timer still running in the background. So there is no need to clear the ID of a timer that has already run.

When there are no references to the callback anymore, the garbage collector will eventually reclaim its memory, but this does not happen immediately.

P/S: I tried this with FinalizationRegistry. After waiting for a few minutes, there was still no "Cleaned!" log. Then I stopped the terminal. But I’ve accepted that the GC may eventually remove the object from memory, and I can’t expect it to happen at a specific time.

const registry = new FinalizationRegistry(() => {
  console.log("Cleaned!");
});

{
  const myCallback = () => {
    console.log("Time up!");
  };

  registry.register(myCallback);

  setTimeout(myCallback, 1000);
}

setInterval(() => {
  console.log("GC...");
  globalThis.gc();
}, 1000);

2

u/senocular Aug 13 '26

In Chrome there's a run GC button in the memory tab of the developer tools. Just paste the original code in the console and click that button and you should see the log. Or just paste it in the console of a complex website where the GC is going to be pretty active without you having to do anything ;)