Explain Codes LogoExplain Codes Logo

Calling a function every 60 seconds

javascript
timers
setinterval
settimeout
Anton ShumikhinbyAnton ShumikhinยทJan 16, 2025
โšกTLDR

Implementing a function every 60 seconds, can be achieved using the setInterval function in JavaScript. The core concept is as follows:

setInterval(() => console.log('Another 60 seconds passed ๐Ÿ˜ฎ'), 60000);

Equivalent to one minute, the script sets a timer triggering an anonymous function at intervals of 60,000 milliseconds. Suit your needs by adjusting the console message or other actions within the arrow function.

For cancelling this timer later, use clearInterval with the interval ID returned by setInterval:

let intervalId = setInterval(() => console.log('Ringing every 60 seconds!'), 60000); // Somewhere in the future, when you want silence clearInterval(intervalId);

If your function is duty-heavy and you worry about overlapping calls, think about using setTimeout in a self-executing function for better control:

function repeatEvery60Seconds() { // The heavy-lifting happens here console.log('A minute has passed, but I am still working ๐Ÿ’ช'); setTimeout(repeatEvery60Seconds, 60000); } // Kick it off repeatEvery60Seconds();

Understanding JavaScript timers

Before going further, comprehend the significant difference between setInterval and setTimeout:

  • setInterval: Executes the function repeatedly at set intervals. However, beware! If the task runs longer than the interval, it may compound calls.
  • setTimeout: Executes the function once after a specified delay. Recursive calls with setTimeout dodge overlapping function calls and permit adjustments to the interval.

Select the method to meet your function's requirements and characteristics.

Strategic usage of JavaScript timers

Code legibility

For better readability and easier debugging, use named functions not anonymous ones:

function logMessage() { console.log("This function's name is logMessage, and I am proud of it ๐Ÿ˜Ž"); } // clear on what's being executed setInterval(logMessage, 60000);

Bottleneck jobs

If your function performs extensive processing, always use the recursive setTimeout pattern to avoid overlapped function calls:

function heavyLifter() { // Solve the mysteries of the universe here... setTimeout(heavyLifter, 60000); } // "Do you even lift, bro?" ๐Ÿ˜‚ heavyLifter();

Checking the DOM

Always ensure DOM elements exist while updating them in intervals to avoid memory leaks:

setInterval(() => { let container = document.getElementById('ice-cream-container'); if(container){ // Check before you fetch ice-cream, else you get a punch(line) in your face! ๐Ÿฆ๐Ÿ˜‚ container.textContent = 'Another scoop every 60s!'; } }, 60000);

Scheduling tools for the wise

Dynamic scheduling

To set dynamic intervals, capture the processing time, and calculate the next call delay:

function performTask() { let start = Date.now(); // Task to perform let end = Date.now(); let duration = end - start; // Is it time for a break yet? ๐Ÿ˜ด setTimeout(performTask, Math.max(0, 60000 - duration)); } performTask();

Practical usage

setInterval is perfect for polling, which makes repeating checks or requests at a regular interval as simple as a walk in the park:

setInterval(() => { fetch('https://api.myapp.com/data') .then(response => response.json()) .then(data => updateDomOrState(data)) }, 60000); // No polling station is opened this frequently ๐Ÿ˜‚

Conditional intervals

You can stop the interval call using certain conditions, saving system resources:

let intervalId = setInterval(() => { if(weGotAWinner()) { clearInterval(intervalId); // Winner, winner, chicken dinner! ๐Ÿ— } // Rest of your code }, 60000);

Using timers responsibly in JavaScript

Timers are a godsend but only with responsible usage:

  • Prevent performance degradation or memory leaks by avoiding unnecessary intervals.
  • Always clear intervals when disposed and on DOM element removals.
  • Remember, setInterval does not guarantee precise call execution, especially on inactive or busy tabs.
  • For precise timing, consider server-side timing or Web Workers.