upog
upog

Reputation: 5531

useEffect - calling a function inside setInterval

How can i call a function inside setInterval of useEffect

useEffect(() => {
        const timeoutId = setInterval(() => {getTime}, 1000); // this is Line 8
        return function cleanup() {
          clearTimeout(timeoutId);
        }
      }, [getTime]);

const getTime=() =>{
            console.log("Inside getTime");}

I want my getTime function to be invoked every 1s. I'm getting below error

 Line 8:46:  Expected an assignment or function call and instead saw an expression  no-unused-expressions.

Another question,I want to update state every 1sec, can i update state inside setInterval

Upvotes: 0

Views: 411

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370759

Your

() => {getTime}

references the getTime function but doesn't do anything with it. You're not calling the function. That's what the linter is warning you about.

Why not pass the getTime function alone into setInterval, without an unnecessary anonymous wrapper?

const timeoutId = setInterval(getTime, 1000);

Also note that since you're setting an interval, not a timeout, you should use clearInterval, not clearTimeout.

can i update state inside setInterval

Sure, but keep in mind that if you have other state variables you want to reference in the process, they may not be up-to-date in the interval's closure. If that's an issue, either use refs as well, or clear and restart the timeout whenever a state variable changes.

Upvotes: 1

wangdev87
wangdev87

Reputation: 8751

You can do if getTime() is the only function for the setInterval

        const timeoutId = setInterval(getTime, 1000);

or as follows if you have other commands in addition to getTime() to do inside the setInterval function.

        const timeoutId = setInterval(() => {getTime()}, 1000);

Upvotes: 2

Related Questions