Vencovsky
Vencovsky

Reputation: 31595

How should I declare a variable that will have the value of setInterval?

I was looking at a question and someone answer it with the code bellow and in the comments someone said

I think instead of assigning undefined we should assign 0 to this.tm. As it's time interval and it should not be undefined.

constructor(props) {
    super(props);       

    this.tm; // With what value should this be declared?
}

timerInterval = () => {        
    this.tm = setInterval(() => {
            ...
    }, 1000);
}

render(){
    return(...)
}

So this made me wonder, what value should it be declared? Changing from undefined to 0 makes any difference?

A reference from docs or something like that would be good to explain it. I couldn't find any.

Upvotes: 0

Views: 377

Answers (2)

Vencovsky
Vencovsky

Reputation: 31595

So, combining all the comments

  • I don't need to declare it in the constructor, I can just use this.tm normally. If I declare it, it's only as a good practice to make the code more clear.
  • This answer have the correct explanation on why it's better to set it to 0, but only in the browser. If it's a node environment, it's better to set it as null.

    On browsers, the handle is guaranteed to be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)

Upvotes: 2

gitcdn
gitcdn

Reputation: 485

The only reason to keep the intervalID is to clear the interval. clearInterval(intervalID) (as well as clearTimeout(intervalID)) will clear the interval or timeout that was set with the ID intervalID, but will do nothing if null, undefined or anything else (such as an invalid or no longer active ID) is passed to them.

So you are free to either initialize your variable with null or not initialize it at all.

Upvotes: 1

Related Questions