DEV Community

Cover image for Canceling setInterval in React

Canceling setInterval in React

Sung M. Kim on September 15, 2018

Photo by Icons8 team on Unsplash Sometimes you need to run a command in an interval using window.setInterval. But if you don’t stop the interval w...
Collapse
 
robertcoopercode profile image
Robert Cooper

Neat tip! Asynchronous code can't be tricky to deal with when unmounting a component. For example, if you call a promise in a component and then immediately unmount the component, the promise call execution will continue :S.

Collapse
 
dance2die profile image
Sung M. Kim

Thanks Robert for the cancelable promise issue.
Wow, I just looked up how to cancel promises and there are so many results and tc39 proposal for cancelable promise has been withdrawn.

How would you cancel the promise call execution?

Collapse
 
robertcoopercode profile image
Robert Cooper

That's a good question, lol. I would have to google it. I've run into the issue in the past, but can't remember how I went about resolving the problem :/

Thread Thread
 
dance2die profile image
Sung M. Kim

If I run into the situation and have to deal with it, I will share.

Thanks for the heads up, Robert πŸ‘Š

Collapse
 
thejoezack profile image
Joe Zack

Great tip, slick solution!

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Thanks Joe.

componentWillUnmount is like Dispose (in C#), which is where you clean up stuff.

But left it out to keep it purely JavaScript

Collapse
 
cgh4vok profile image
cg-h4voK

So basic and yet I had completely forgotten about this! Thank you so much!!

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome 😎 & thanks for the feedback there cg-h4voK πŸ™

Collapse
 
automobileslie profile image
Carlie Anglemire

Thank you! This was really helpful.

Collapse
 
arjobansingh profile image
Arjoban Singh

Hey, i did the same way you did here, but still my app using Reactnative showing error about - cant perform react state update on unmounted component, memory leak error

Collapse
 
dance2die profile image
Sung M. Kim

I am not familiar with RN and do you have a code snippet or runnable sample (Expo?)

The way it's handled is different w/ introduction of hooks too.