Skip to main content

Call a Function Repeatedly in JavaScript

In JavaScript, there are several ways to call a function repeatedly.

The most common method is to use a loop, such as a for or while loop. This approach allows you to control how many times the function is called as well as the order in which it is called.

Another option is to use the setInterval() method, which will call a function at regular intervals. This can be useful for animations or other time-based tasks.

Finally, you can also use recursion, which is when a function calls itself. This can be an effective way to solve certain types of problems, but it can also lead to infinite loops if not used carefully. Whichever method you choose, calling a function repeatedly can be a powerful tool in your JavaScript apps.

In this article, we will only give examples about setInternal method.

Call A Function Every 10 Seconds

In JavaScript, you can call a function on every defined internal by using the setInterval() function. This function takes two parameters: the first is the name of the function to call, and the second is the number of milliseconds between calls. For example, these codes will call the printLine() function every defined interval:

function printLine(){
setInterval("printLine", 10000);
    console.log("This line is printed to console on every 5 seconds");
}, 5000);
//store the id in order you need it to clear this repeated task
var intervalId = window.setInterval(function(){
    console.log("This line is printed to console on every 5 seconds");
}, 5000);

By continuing to use the site, you agree to the use of cookies.