Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearTimeout isn't clearing the timeout

Tags:

javascript

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?

like image 980
abyrne85 Avatar asked Oct 23 '18 19:10

abyrne85


People also ask

Does clearTimeout clear all timeouts?

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.

How do I clear a timeout set?

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.

What happens if setTimeout is not cleared?

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.

How do you delete a timeout in a function?

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.


1 Answers

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.

like image 163
Scott Marcus Avatar answered Nov 14 '22 23:11

Scott Marcus