Repetitive Asynchronous Tasks with JavaScript's setInterval()

Hero image for Repetitive Asynchronous Tasks with JavaScript's setInterval(). Image by Agê Barros.
Hero image for 'Repetitive Asynchronous Tasks with JavaScript's setInterval().' Image by Agê Barros.

When developing with JavaScript, managing timebound and repetitive tasks is often achieved by using the setInterval() function. Very much a close relative to setTimeout(), the setInterval method is pivotal when it comes to executing a function or a block of code repeatedly, at fixed time intervals.


What is setInterval()?

setInterval is a global JavaScript method which can be used to call a function or execute a code snippet repeatedly, with a fixed delay between each call. It's part of the Window interface in the browser environment, making it widely available for webbased scripts.

Basic Syntax

setInterval(function, delay, ...args);
  • function: The function to be executed.
  • delay: The interval time in milliseconds between each function call.
  • ...args: Additional arguments to pass to the function.

Using setInterval in JavaScript

Starting an Interval

To start an interval, you simply call setInterval, providing the function to be executed and the interval time, like this:

const sayHello = (): void => {  console.log('Hello, world!');};setInterval(sayHello, 2000);  //=> 'Hello, world!' every 2 second

This example will feel extremely familiar if you've also read my previous article about setTimeout, they are quite genuinely virtually identical. However, whereas the example code I used there would output Hello, World! once, after two seconds (2000 milliseconds), in this instance it will output it repeatedly, once every two seconds.

Stopping an Interval

This will simply repeat until the end of time (or the end of that browsing session), so it's important to be able to stop it too. My code example above it an anonymous function tied to the root, however, if we declare it as a variable beforehand, we can then stop is again by using clearInterval:

const sayHello = (): void => {  console.log('Hello, world!');};// set as 'interval' this timeconst interval = setInterval(sayHello, 1000);// we can stop this again like this:clearInterval(interval);

setInterval in React

In dynamic web applications, especially those using frameworks like React or Vue, managing intervals requires careful attention to the application's lifecycle. You need to ensure that intervals are cleared when components or pages are unloaded to prevent unwanted side effects or resource leaks.

This is very simple if for example you are setting the interval within a useEffect hook:

useEffect(() => {  const timer = setInterval(() => {    // Outputs 'tick' every second:    console.log('tick');  }, 1000);  // makes sure that the timer is cleaned up in the return  return () => clearInterval(timer);}, []);

Here, I'm using setInterval within a useEffect to create a timer which outputs 'tick' every second. With an empty dependency array ([]), the hook only triggers once, at the point the component mounts which means that this interval will start as soon as the component mounts.

Because I've assigned the interval to a variable (timer), we then add clearInterval to the hook's return, ensuring that it is cancelled at the point the component is unmounted again.


Considerations and Best Practices


Wrapping up

Understanding setInterval is crucial for handling repetitive tasks in JavaScript. Whilst it's a powerful tool for periodic executions, you need to be aware of how to manage intervals responsibly, especially in complex applications.


Categories:

  1. Adaptive Development
  2. Cross‑Browser Compatibility
  3. Development
  4. Front‑End Development
  5. Guides
  6. JavaScript
  7. Responsive Development