[EDIT] - Added a bit more detail to the code sample.
I'm trying to build a timer component. This is my code.
const Timer = () => {
let startTime;
const handleStart = () => {
startTime = Date.now();
console.log(startTime);
};
const handleEnd = () => {
console.log(startTime);
};
return (
<>
<button
onClick={handleStart}
>
Start timer
</button>
<button
onClick={handleEnd}
>
End timer
</button>
</>
)
}
handleStart is the click handler for one button and handleEnd is the click handler for the second button.
The problem
When I click the first button to start the timer, everything works and the value of startTime is logged to the console, so I know it has been assigned. However, when I click the second button to stop the timer, it doesn't log startTime. Instead, the console output is undefined.
I have no idea why this is happening. Can someone explain why this code isn't working?