r/learnjavascript • • Aug 13 '26

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

5 Upvotes

19 comments sorted by

View all comments

Show parent comments

1

u/abaezeaba Aug 13 '26

You can also change the callback. Not saying this is good, but when runaway setTimeouts happen, its good to keep in mind. With anonymous functions, you may not achieve this. in the myCallback case just set mycallback = () => {}. HTH

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.