Reputation: 31595
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 assign0
tothis.tm
. As it's time interval and it should not beundefined
.
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
Reputation: 31595
So, combining all the comments
this.tm
normally. If I declare it, it's only as a good practice to make the code more clear.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
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