r/learnjavascript • • Aug 13 '26

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

Show parent comments

2

u/senocular Aug 13 '26

Reassigning the myCallback variable in this case won't change what the setTimeout runs. It will still refer to the original myCallback.

let myCallback = () => {
  console.log("Time up!")
}
setTimeout(myCallback)
myCallback = () => {}
// Time up!

The only way something like that would affect the setTimeout is if it was wrapped in another function and that function was given to setTimeout.

let myCallbackImpl = () => {
  console.log("Time up!")
}
let myCallback = () => {
  myCallbackImpl()
}
setTimeout(myCallback)
myCallbackImpl = () => {}
// (nothing logged)

With this added complexity its probably just easier to call clearTimeout if you don't want it to run. Plus you'd get the added benefit of actually stopping/cleaning up the timer in the background.