Timeout id is not cleared in Javascript

Viewed 38

I have this code:

let ad1 = setTimeout(() => {
  console.log("Delayed for 1 second.");
}, "1000")
console.log(ad1, 'start')
clearTimeout(ad1)
console.log(ad1, 'end')

Here console.log(ad1, 'end') i expect that my ad1 should be cleared but the id still there.
Why the id is not cleared and how to see if the timeout id is clearead in my situation?

1 Answers
  • It does get clear out.
  • So what's going on here is that this setTimeout return one ID that is stored in ad1, which immediately clearout because of synchronised nature of javascript.
  • and then it will run line by line which prints start and end.
  • Here below in my code it won't print start because I moved that console.log("start") in setTimeout.
  • where as console.log("end"), which will be printed because it's not in side of setTimeout.

console.log("JavaScript is a synchronous, blocking, single-threaded language.");
let ad1 = setTimeout(() => {
  console.log(ad1, 'start')
  console.log("Delayed for 1 second.");
}, 1000)
clearTimeout(ad1)
console.log(ad1, 'end', "not inside setTimeout");

Related