There are instances when we need to execute a piece of code for multiple iterations at specified intervals. JavaScript comes with some amazing built-in objects and functions and two such functions which solve our problem are setInterval(callback, interval) and setTimeout(callback, delay), where these functions schedule the next execution of the callback function after the specified delays or intervals.
Let’s go out with the comparison of two pieces of code
Code Snippet 1: Using setInterval()
const [currentTime, setCurrentTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date());
}, 1000);
// Clean up the timer when the component unmounts
return () => {
clearInterval(timer);
};
}, []);
const formattedTime = currentTime.toLocaleTimeString([], {
hour: "numeric",
minute: "2-digit",
});
return (
<div className="header">
<span className="current-time">{formattedTime}</span>
</div>
);
Here we are setting up and managing a timer in the useEffect hook of React that runs a function setCurrentTime(new Date()) every 1000 milliseconds (1 second) to update the current time every second which is being used in our application’s header after formatting with formattedTime.