lamsmallsmall
lamsmallsmall

Reputation: 125

Is setInterval executed right upon declaration?

I was learning React and I saw this example, which is just a simple timer:

export default function Timer() {


const [time, setTime] = useState(0);
  
  const intervalId = setInterval(() => {
  setTime((prev) => prev + 1);
  }, 1000);

  useEffect(()=>{
    return () => {
  clearInterval(intervalId);
  };
  });

  return (
    <>
      <h1>Time: {time}</h1>
    </>
  );
}

The timer automatically starts when I run this code, I wonder why is it that I never called intervalId after declaring it and it still runs automatically. So I am curious if setInterval is executed right upon declaration?

Upvotes: 0

Views: 142

Answers (1)

Quentin
Quentin

Reputation: 943608

Is setInterval executed right upon declaration?

Yes. You pass it a function, it calls that function every interval.

I never called intervalId

The ID is an identifier used to stop the function from being called again. That is why you pass it to clearInterval.

Upvotes: 1

Related Questions