Welcome to a tutorial on how to run Javascript every second. So you want to loop a piece of code endlessly and have it fire up every second (or every X seconds)?
The easiest way to run Javascript every second is to use the setInterval()
function. For example:
function foo () { console.log("RUNNING"); }
setInterval(foo, 1000);
That covers the quick basics, but let us walk through a few actual examples in this guide. Read on!
TLDR – QUICK SLIDES
[web_stories_embed url=”https://code-boxx.com/web-stories/run-javascript-every-second/” title=”How To Run Javascript Every Second” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]
Fullscreen Mode – Click Here
TABLE OF CONTENTS
RUN JAVASCRIPT EVERY SECOND
All right, let us now get started with examples of how to loop Javascript every second.
METHOD 1) INTERVAL TIMER
<!-- (A) CURRENT TIME WILL BE SHOWN HERE -->
<div id="timeNow"></div>
<script>
// (B) RUN THIS FUNCTION EVERY SECOND TO UPDATE HTML
var showTime = () => {
let now = new Date(),
hr = now.getHours(), min = now.getMinutes(), sec = now.getSeconds();
document.getElementById("timeNow").innerHTML = `${hr}:${min}:${sec}`;
};
// (C) START INTERVAL
var timer = setInterval(showTime, 1000);
// TO STOP - clearInterval(timer);
</script>
As in the introduction snippet:
- (B) Start by creating the function that you want to run every second. In this example, it is
showTime()
. - (C) Use
setInterval(FUNCTION, DELAY)
to create an interval timer. This will fire the givenFUNCTION
for everyDELAY
microsecond. I.E. 1000 ms is equal to 1 sec.
METHOD 2) RECURSIVE FUNCTION
<!-- (A) CURRENT TIME WILL BE SHOWN HERE -->
<div id="timeNow"></div>
<script>
// (B) RUN THIS FUNCTION EVERY SECOND TO UPDATE HTML
var showTime = () => {
// (B1) UPDATE HTML
let now = new Date(),
hr = now.getHours(), min = now.getMinutes(), sec = now.getSeconds();
document.getElementById("timeNow").innerHTML = `${hr}:${min}:${sec}`;
// (B2) LOOP
timer = setTimeout(showTime, 1000);
};
// (C) START!
var timer = setTimeout(showTime, 0);
// TO STOP - clearTimeout(timer);
</script>
Another simple trick that we use. Take extra note of (B2), the function sets itself on a 1-second timeout and calls itself recursively.
METHOD 3) INFINITE LOOP
<!-- (A) CURRENT TIME WILL BE SHOWN HERE -->
<div id="timeNow"></div>
<script>
// (B) RUN EVERY SECOND TO UPDATE TIME
var showTime = async () => { while (true) {
// (B1) UPDATE CURRENT TIME
let now = new Date(),
hr = now.getHours(), min = now.getMinutes(), sec = now.getSeconds();
document.getElementById("timeNow").innerHTML = `${hr}:${min}:${sec}`;
// (B2) WAIT FOR 1 SECOND
await new Promise(resolve => setTimeout(resolve, 1000));
}};
// (C) START!
showTime();
</script>
Lastly, this is a funky “modern solution”.
- (B) The basic idea is to create an endless
while (true)
loop. But since this will block and “hang” the entire page, it can only be done in anasync function()
. - (B2) At the end of each cycle, we do an
await new Promise(resolve => setTimeout(resolve, 1000))
. This is kind of confusing, but it basically waits for 1 second before looping itself.
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.
WHICH IS BETTER? WHICH IS CORRECT?
Personally, I prefer setInterval()
. It is the most traditional method and easiest to understand. While some people may argue that the infinite async-while-function
works better, because it runs in parallel – I will say, just pass an async function
into setInterval()
then. 🙄
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!