R
R
RomanSS2017-01-28 16:36:20
JavaScript
RomanSS, 2017-01-28 16:36:20

I can't understand how react works with setInterval & setTimeout?

Help me understand and understand how setInterval works in React, or is it a feature of javascript, I can’t understand.
When the component is loaded, I broadcast in the "componentDidMount" setInterval with the execution of requests to the server, the requests go away, everything is fine.
If this component is not active (unmounted), requests stop, i.e. setInterval stops working, although I did not kill it with the clearInterval function, the question arises why? (although it seems to be logical, the component was killed, setInterval was also killed), but then another question arises, it is not killed, but simply stops, because when I reactivate this component, two setIntervals already start working for me simultaneously (the first from the first display , second from second) i.e. the component stores information on it, but how does it stop it then, when the component is unmounted, requests to the server stop after all, so setInterval somehow turned off?
Well, an additional question, is it possible somehow in react to kill all the setIntervals running in it at once in the component, or will it be necessary to store, for example, the id of the running intervals in an array?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Bobylev, 2017-01-28
@RomanSS

Intervals cannot automatically stop unless their ID has been stored and clearInterval has been explicitly called.
Same thing with React. Even if the component has become inactive intervals will be executed. So if you don't want leaks, keep the identifiers and explicitly call clearInterval in componentWillUnmount.
Here's an example: https://jsbin.com/zefopuw In the console you will see that even though the components have been removed - the intervals still work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question