Trying to clear a timeout and its not working. console.logging it returns a number after its been initialized and after it's been destroyed.
const timer = setTimeout(() => {});
console.log('initialised', timer); // initialised 22
clearTimeout(timer);
console.log('destroyed', timer); // destroyed 22
I'm expecting the second log to return null. I also didn't expect the timer to be a simple number. I would have expected it to be an object. Is clearTimeout doing what it should be doing here?
The global clearTimeout() method cancels a timeout previously established by calling setTimeout() . If the parameter provided does not identify a previously established action, this method does nothing.
To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.
In other words, it's a no-op; nothing happens, and no error will be thrown. Save this answer. Show activity on this post. You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens.
The clearTimeout() function in javascript clears the timeout which has been set by setTimeout()function before that. setTimeout() function takes two parameters. First a function to be executed and second after how much time (in ms). setTimeout() executes the passed function after given time.
The timer
variable holds a unique number that represents a particular timer. Clearing the timer stops the asynchronous operation, but your variable is still just that, a variable, and it will hold the last value you gave it unless it goes out of scope or your assign something else to it.
The best proof that your code is working as it should is to give the timer callback function some behavior and see if that behavior is correct. With your code, we'll see that the timer callback function never actually runs (no message from the callback function is ever written to the console) because you are cancelling it before the function that created it completes. We don't need extra console.log()
statements beyond that one.
const timer = setTimeout(() => { console.log("The timer function has run!" ); });
clearTimeout(timer);
NOTE: In most cases, we don't need to know the actual value of the timer
variable. We only need to store it to kill its corresponding timer operation later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With