Automatically Repeat JavaScript Function Every X Seconds

- 1 minute read

In JavaScript, we can use the built-in setInterval() function to repeat any given function over a certain interval:

const myFunction = () => {
    console.log(`Hello world!`);
};

setInterval(myFunction, 2000); // Repeat myFunction every 2 seconds

setInterval() takes two parameters. The first parameter is the function to be executed, and the second parameter is the number of milliseconds that must pass before the function is executed again.

While setting a timeout runs a function just once after a given waiting period, setting an interval runs a function indefinitely after a given waiting period (unless the interval has been “cleared”).

Link to this section Clearing an interval

By clearing an interval with clearInterval(), you can stop it from continuing to execute its function after each delay:

const interval = setInterval(() => console.log(`Hello world!`), 2000);

clearInterval(interval); // The interval will no longer run

Link to this section Conclusion

Thanks for reading!

This is especially useful for automatically refreshing dynamic values that might frequently change.