← Back to Blog

Clearing Timeouts and Intervals Before They Trigger

javascript

By Kevin Hou

1 minute read

I've been working a lot with time and animation and one of the things that I had to overcome was preventing an existing timeout from triggering. I had already declared a timeout with setTimeout, but I wanted to cancel it midway. My solution was to first declare an empty variable at the top of my React code. This line goes even before you create your class:

1var myTimeout; 2 3module.exports = React.createClass({ 4 ... 5}); 6

Next, I set my interval equal to a global variable like so:

1myTimeout = setTimeout(functionName, 500); 2

My interval is now set to 'myTimeout' and because I declared this variable globally, it can be accessed at any scope. If I want to cancel my timeout before it has triggered I use the clearTimeout function:

1clearTimeout(myTimeout); 2

That's it! It's really simple. This works with intervals as well. Simply set the inveral globally using the same method as described above and clear the interval with clearInterval(myInterval).

Hope this helps!