Grip
Grip

Reputation: 25

React JS - why is this variable behaving like a function?

I created a countdown timer, but I couldn't get the interval to clear with clearInterval(). I eventually made the setInterval function be inside of a variable, then passed that variable as an argument in clearInterval(). What I don't understand is why is the setInterval function being called in the first place, because all I'm doing is creating a variable. Do functions inside variable automatically run? Do you not have to call them somehow (how you you even call it if it's inside a variable?). Here is the code that works, but I don't understand why:

myFunct () {
  const intervals = setInterval(() => {
    if(this.state.time > 0) {
      this.setState({ time: this.state.time-1 })
    }
    else {
      clearInterval(intervals);
    }
  }, 1000);
}

Upvotes: 0

Views: 110

Answers (1)

Pandemonium
Pandemonium

Reputation: 8390

Here is the signature of setInterval:

window.setInterval(callbackFn, delay, param1, param2, ..)

This function returns a number, representing the ID value of the timer that is set. This number can be passed to window.clearInterval to clear the timer. So when you call it like this:

const myInterval = setInterval(myCallback, 1000);

myInterval is now a number ID for the timer being run. If myCallback calls clearInterval(myInterval), it clears the timer.

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

Upvotes: 1

Related Questions