Explain Codes LogoExplain Codes Logo

Javascript: get code to run every minute

javascript
prompt-engineering
interview-preparation
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 13, 2025
TLDR

To execute a function every minute in JavaScript, you can make use of the setInterval() function, providing an interval of 60000 milliseconds (representing 60 seconds). We've got a simple example for you right below:

setInterval(() => console.log('60 seconds have passed, human.'), 60000);

Advanced timing techniques

Making your timer tick-tock precisely

While setInterval() is great, it's not NASA-grade precise. Delays can sometimes occur due to long-task execution or JavaScript's event queue getting busy. You can mitigate this by tracking the expected execution times:

let expected = Date.now() + 60000; setInterval(() => { const drift = Date.now() - expected; // Drift? More like "being fashionably late." expected += 60000; console.log('Handled drift: ', drift); }, 60000);

Scheduling the initial run

If you want your code to kick off at the start of each minute, you might need to calculate the delay for its inaugural setTimeout():

const startOfNextMinute = (new Date()).setSeconds(0, 0) + 60000; const timeToNextMinute = startOfNextMinute - Date.now(); // "But why is it always a minute longer..." setTimeout(() => { myFunction(); // Swappable with your function // Kicking off the interval setInterval(myFunction, 60000); }, timeToNextMinute);

Interval halting made easy

To put an end to an interval, grasp the interval ID that gets returned by setInterval(). Make it stop, please!

const intervalId = setInterval(() => console.log('Hello!'), 60000); // Say "Hello!" every minute. // When you've enough of "Hello!" clearInterval(intervalId); // Quoth the raven, "Nevermore."

Utilizing setTimeout for precise initial run

Perfect start for perfectionists

If minute accuracy is key and you need to match the clock beats, setTimeout can be utilized to set the first execution right at the start of the forthcoming minute:

function executePrecisely() { // Calculating our wait time till the next minute const now = new Date(); const delay = 60000 - (now.getSeconds() * 1000 + now.getMilliseconds()); setTimeout(function startInterval() { myFunction(); // The code you wish to execute setInterval(myFunction, 60000); // And now we wait again. }, delay); } executePrecisely(); // Let's get this party started!

Evasive maneuvers for delays

By using setTimeout, you ensure there's no unnecessary lag between your code readiness and when the next minute takes off . Kind of like waiting for the green signal to bingo at the exact moment.

Cleaner code approaches

Going for named functions

Instead of playing hide and seek with anonymous functions, always go with named functions with setInterval for superior readability and maintainability:

function performAction() { // Your action here } setInterval(performAction, 60000);

Distributing responsibilities

Keep your timing logic and task execution playing their own parts by keeping them separate, making your code much more straightforward:

function timerCallback() { performAction(); updateState(); // Define me! } // Look ma, clean and understandable timer! const intervalId = setInterval(timerCallback, 60000);