1

I was a looking for a valid way to check if timeout still exists in order to clear it before. But realised it's number all the time at least in latest Chrome and Safari. I will appreciate a lot if somebody could shine some line on this case:

const timeout = setTimeout(() => {
  // do magic
}, 100000)

console.log(typeof timeout) // number (makes sense)

clearTimeout(timeout)
console.log(typeof timeout) // number (...hmm)

setTimeout(() => {
  console.log(typeof timeout) // number --> magic ¯\_(ツ)_/¯
}, 1000)
volna
  • 2,452
  • 4
  • 25
  • 61
  • FWIW calling clearTimeout on one that doesn't exist doesn't cause any errors. – jhpratt Jul 22 '19 at 21:25
  • Why you want to check if it hasn't been cancelled before? calling clearTimeout won't cause any error even if the timer stopped before. – E.Omar Jul 22 '19 at 21:32
  • @E.Omar since in my business logic clearing timeout attached as a simple hook on the logic that can be executed pretty frequently. Something deeps inside tells me that checking for timeout if it's exists is "cheaper" then just trying to clear it all the time – volna Jul 23 '19 at 08:44
  • For people who are interested why assigning timer to variable always returns number: https://stackoverflow.com/questions/10068981/what-does-settimeout-return/19375604 – volna Jul 23 '19 at 17:17

3 Answers3

2

clearTimeout does remove the callback from the timer queue. It does not alter the timeout variable that you used to store the identifier value - especially since you declared it as const.

I was a looking for a valid way to check if timeout still exists

Use let timeout and set it to null or undefined when you clear it.

in order to clear it before

or just always call clearTimeout, it doesn't do any harm if the timer has already been cleared before or did run.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

How about setting timeout to undefined when you clear it (and possibly when the timeout runs, depending on your usecase):

 clearTimeout(timeout);
 timeout = undefined;

That way you can then easily check if the timeout is done with

  if(timeout) /* do stuff */

(You have to change const timeout to let timeout then)

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

setTimeout (also setInterval and requestAnimationFrame) return number with id of process so you can cancel it later. So when you call clearTimeout(id) process is cancelled. But primitive values, amont which there is number, are copied so once you assigned the number to variable, it stays there.

Calling cleatTimeout(id) for process that has been already cancelled doesn’t cause any error.

The Witness
  • 910
  • 7
  • 12