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&nbsp;<strong><em>setInterval(callback, interval)</em></strong>&nbsp;and&nbsp;<strong><em>setTimeout(callback, delay),&nbsp;</em></strong>where these functions schedule the next execution of the&nbsp;<em>callback</em>&nbsp;function after the specified&nbsp;<em>delays</em>&nbsp;or&nbsp;<em>intervals</em>.</p> <p><strong>Let&rsquo;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(() =&gt; { const timer = setInterval(() =&gt; { setCurrentTime(new Date()); }, 1000); // Clean up the timer when the component unmounts return () =&gt; { clearInterval(timer); }; }, []); const formattedTime = currentTime.toLocaleTimeString([], { hour: &quot;numeric&quot;, minute: &quot;2-digit&quot;, }); return ( &lt;div className=&quot;header&quot;&gt; &lt;span className=&quot;current-time&quot;&gt;{formattedTime}&lt;/span&gt; &lt;/div&gt; );</pre> <p>Here we are setting up and managing a timer in the&nbsp;<strong><em>useEffect</em></strong>&nbsp;hook of React that runs a function&nbsp;<em>setCurrentTime(new Date())&nbsp;</em>every 1000 milliseconds (1 second) to update the current time every second which is being used in our application&rsquo;s&nbsp;<em>header</em>&nbsp;after formatting with&nbsp;<em>formattedTime.</em></p> <p><a href="https://blog.stackademic.com/overlapping-executions-with-setinterval-in-js-2583a905b22c">Click Here</a></p>