import React from "react";
function App() {
let time = new Date().toLocaleTimeString();
const [Time, setTime] = React.useState(time);
function getTime() {
time = new Date().toLocaleTimeString([], { hour12: false });
//console.log(time);
setTime(time);
}
setInterval(getTime, 2000);
return (
<div className="container">
<h1>{Time}</h1>
<button onClick={getTime}>Get Time</button>
</div>
);
}
export default App;
This is the App component of React.js. This code is creating a running clock. When I'm commenting out the setInterval function, console.log is working fine, but as soon as I'm enabling that function, everything on the main screen works fine, but on the console screen, console.log(time) is running infinite times. Please help. Thanku.
setInterval()is for. The timer keeps running until something stops is.getTime()will be called every 2 seconds.