I wanted to know if someone can explain the working of scope with respect to let keyword.
import "./styles.css";
import { useEffect, useReducer, useState } from "react";
export default function App() {
const [counter, setCounter] = useState(0);
let intervalId;
const handleCounter = () => {
intervalId = setInterval(() => {
setCounter((prevState) => prevState + 1);
}, 1000);
console.log("intervalId in counter:", intervalId);
};
const handlePause = () => {
console.log("intervalId:", intervalId);
clearInterval(intervalId);
};
return (
<div className="App">
<h1>Counter-{counter}</h1>
<button onClick={handleCounter}>Start</button>
<button onClick={handlePause}>Pause</button>
</div>
);
}
This is my code above, Firstly, I click on start button which triggers handleCounter(). When I try to save the setInterval id in “intervalId” variable which is a let variable and then try to clear the interval as in handlePause(). I get “undefined” in console and the counter doesn’t stops.
P.S:
I understand that if I try to save the id in a state and then try to clear the interval, that will be the fix. But, I am more interested in knowing why with let function scope, it won’t work?