Overlapping Executions with setInterval() in JS
<p>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 <strong><em>setInterval(callback, interval)</em></strong> and <strong><em>setTimeout(callback, delay), </em></strong>where these functions schedule the next execution of the <em>callback</em> function after the specified <em>delays</em> or <em>intervals</em>.</p>
<p><strong>Let’s go out with the comparison of two pieces of code</strong></p>
<p><strong>Code Snippet 1</strong>: Using setInterval()</p>
<pre>
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>
);</pre>
<p>Here we are setting up and managing a timer in the <strong><em>useEffect</em></strong> hook of React that runs a function <em>setCurrentTime(new Date()) </em>every 1000 milliseconds (1 second) to update the current time every second which is being used in our application’s <em>header</em> after formatting with <em>formattedTime.</em></p>
<p><a href="https://blog.stackademic.com/overlapping-executions-with-setinterval-in-js-2583a905b22c">Click Here</a></p>