I have a button on which I need to call a setInterval but if the interval is already set then I don’t want to initiate another setInterval.
So this is how I have implemented it ():
export default function App() {
const [intervalId, setIntervalId] = useState(null);
const startInterval = () => {
console.log("inside startInterval", intervalId);
if (!intervalId) {
console.log("starting Interval", intervalId);
const _intervalId = setInterval(() => {
console.log("Interval Id inside setInterval is", intervalId);
}, 2 * 1000);
setIntervalId(_intervalId);
} else {
console.log("Rejecting set interval");
}
};
const onBtnClick = () => {
console.log("btn clicked");
// make API call
startInterval();
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={onBtnClick}>Click Me</button>
</div>
);
}
but inside setInterval I always get to see the default value of state i.e. null in my case.
How can I access the latest value inside setInterval?
Your code is working. While the log shows the
intervalId
asnull
, that’s only because the function that the interval closes over was initialized when theintervalId
was indeednull
.A variable declared with
const
can’t be reassigned; theintervalId
starts out asnull
during the render when the button is clicked, and thestartInterval
function closes over thatnull
. WhenstartInterval
is called, and the anonymous callback is declared:it still closes over the
null
intervalId
.If you wanted to see the interval ID inside the callback, use a ref instead.
Byzadu – Generic viagra canada viagra next day
Bladak – zithromax Sgzmvv fnjlet