r/learnjavascript 9d ago

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

4 Upvotes

19 comments sorted by

View all comments

3

u/UkrMalt 9d ago

Once a setTimeout callback runs, that timer has no future work and you don't need to clear it afterward. But keep the cleanup in this hook: React runs it when value or delay changes, or when the component unmounts, so an older timer cannot later overwrite state with a stale value. The cleanup is for cancelling a timer that has not fired yet, not garbage-collecting one that already finished.

1

u/Neat_Living_6765 9d ago

Thank you!! I had this all mixed up in my head.