How to call a function repeatedly every 5 seconds in JavaScript?


We will use the setInterval() function to repeatedly call a function every 5 seconds. This function takes two arguments, the first being the function to call and the second being the interval time in milliseconds.

JavaScript setInterval

  • setInterval() is a JavaScript function that allows you to execute a function repeatedly at a specified interval (in milliseconds).

  • It returns a unique ID that can be used to clear the interval with the clearInterval() method.

  • It can be useful for tasks such as periodically updating a page or creating animations.

  • It takes two arguments, the function to be executed, and the interval time in milliseconds.

  • It will continue to execute the function until it is cleared using clearInterval() or the page is closed.

Approach

You can use the setInterval() function to call a function repeatedly every 5 seconds in JavaScript.

setInterval(myFunction, 5000);

The first argument is the function you want to call, and the second argument is the interval time in milliseconds. In this example, the function myFunction will be called every 5 seconds (5000 milliseconds).

You can stop the interval by calling the clearInterval() function and passing the return value of setInterval() as the argument −

let intervalId = setInterval(myFunction, 5000);
clearInterval(intervalId);

Example

Here is an example of how to call a function repeatedly every 5 seconds in JavaScript using the setInterval() function −

function myFunction() {
   console.log("Hello World!");
}
setInterval(myFunction, 5000);

The setInterval() function takes two arguments: the first argument is the function that you want to call, and the second argument is the interval time in milliseconds. In this example, the myFunction function is called every 5,000 milliseconds, or 5 seconds.

The setInterval function returns a unique ID which can be passed to the clearInterval function to stop the function from being called repeatedly −

let intervalId = setInterval(myFunction, 5000);
clearInterval(intervalId);

This code creates an interval that calls the myFunction function every 5 seconds (5000 milliseconds). The function will keep running until the website is closed or the interval is cleared.

Output

Updated on: 16-Feb-2023

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements