Home  >  Article  >  Web Front-end  >  How to call a function repeatedly every 5 seconds in JavaScript?

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

WBOY
WBOYforward
2023-08-24 16:53:012547browse

We will use the setInterval() function to repeatedly call a function every 5 seconds. This function accepts two parameters, the first is the function to be called and the second is the time interval in milliseconds.

The Chinese translation of

JavaScript setInterval

is:

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 using the clearInterval() method.

  • It can be used for tasks such as updating pages regularly or creating animations.

  • It accepts two parameters, the function to be executed and the interval in milliseconds.

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

method

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

setInterval(myFunction, 5000);

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

You can stop interval execution by calling the clearInterval() function and passing the return value of setInterval() as a parameter.

let intervalId = setInterval(myFunction, 5000);
clearInterval(intervalId);
The Chinese translation of

Example

is:

Example

The following is an example of using the setInterval() function to repeatedly call a function every 5 seconds in JavaScript:

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

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

The setInterval function returns a unique ID that can be passed to the clearInterval function to stop calling the function repeatedly -

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

This code creates an interval that calls the myFunction function every 5 seconds (5000 milliseconds). This function continues to run until the site is closed or the interval is cleared.

Output

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

The above is the detailed content of How to call a function repeatedly every 5 seconds in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete