0

I have a function that starts a timer:

startTimer() {
    this.timer = setInterval(() => {
        let newCount = this.state.count -1;
        this.setState({
            count: newCount >= 0 ? newCount : 0
        });
        if(newCount === 0) {
            this.setState({countdownStatus: 'stopped'});
        }
    }, 1000)
}

Now when my React component unmounts, I want to remove the timer from memory. So what I am currently doing is this:

componentWillUnmount() {
    clearInterval(this.timer);
    this.timer = undefined;
}

Is there a way to get rid of the timer altogether, without setting it to undefined?

Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163
  • @T.J.Crowder - why does the question in the duplicate answers the current question, when he doesn't need to remove the timer property at all? – Ori Drori Jan 02 '17 at 11:38
  • 1
    Is there any particular reason you need this? The result of `setInterval()` is just a number that has no meaning after you've cleared it. If you want to get rid of it you can just set it to undefined if you want. Alternatively you could `delete` it. – Robba Jan 02 '17 at 11:40
  • @OriDrori: The OP's said he wants to remove it rather than setting it to `undefined`. Or perhaps the question is unclear... – T.J. Crowder Jan 02 '17 at 11:40
  • @T.J.Crowder - indeed, but he doesn't understand that `this.timer` is not a pointer to an object, just the id of the timer. So the "duplicated" is technically right, but doesn't fit the intent. – Ori Drori Jan 02 '17 at 11:41
  • @OriDrori: Well, the way I read it, it does; I don't read that they believe there's still something left other than the property even after assigning `undefined`. Until/unless the OP comes back to clarify, we can't know if you're correct that they believe something else is going on... – T.J. Crowder Jan 02 '17 at 11:43
  • @MihaŠušteršič - why do you want to remove `this.timer` after clearing it? – Ori Drori Jan 02 '17 at 11:57
  • @T.J.Crowder You are corrent, after clearing the interval I would like to also remove the id of the timer - there is no use in keeping it around since the next time my component starts, the timer will be created anew, which could potentialy result in storing too many ids in memory, if you let the app running for a week or so – Miha Šušteršič Jan 02 '17 at 11:58
  • @MihaŠušteršič: *"... the timer will be created anew, which could potentialy result in storing too many ids in memory."* No, nothing to worry about there. When you do `this.timer = undefined`, you've completely removed the timer's handle (which is just a number anyway, on browsers), and `clearInterval` has already done all other necessary cleanup. The next time your comp starts, it just overwrites that `undefined` with a new handle (the new number). So just setting `undefined` is fine, and has the advantage that it won't make the JavaScript engine de-optimize the object, which `delete` can do. – T.J. Crowder Jan 02 '17 at 12:09

0 Answers0