Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a timeout has been cleared?

Tags:

javascript

I am wondering is there a way to tell if a timeout is still set

var t=setTimeout("alertMsg()",3000); 

I thought t would be like undefined when you clear it. But it seems to have some id that does not get cleared.

like image 782
chobo2 Avatar asked Mar 07 '11 23:03

chobo2


People also ask

How do I clear set timeout?

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?

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. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.

Does clearTimeout clear all timeouts?

It will clear all the timeouts, as setTimeout is an Asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack, thus clearAllTimeout runs and cancels them before they can be executed.


1 Answers

Not directly, but you can create a wrapper object to give that functionality. A rough implementation is like so:

function Timeout(fn, interval) {     var id = setTimeout(fn, interval);     this.cleared = false;     this.clear = function () {         this.cleared = true;         clearTimeout(id);     }; } 

Then you can do something like:

var t = new Timeout(function () {     alert('this is a test'); }, 5000); console.log(t.cleared); // false t.clear(); console.log(t.cleared); // true 
like image 69
Reid Avatar answered Oct 04 '22 13:10

Reid