Repeatedly call a function in JavaScript
This post will discuss how to repeatedly call a function or execute the specified code in JavaScript.
1. Using setInterval() method
The following solution uses the setInterval() method to repeatedly call a function with a specified time delay between each call. To stop the timer, pass the return value of setInterval() to the clearInterval() method.
|
1 2 3 4 5 6 7 8 9 |
const x = 2; // 2 seconds function fun() { console.log(`Called after ${x} seconds…`); } setInterval(function() { fun(); // does some work }, x * 1000); |
2. Using setTimeout() method
Another approach is to use the setTimeout() method, which is used to execute a function or code snippet once the specified time is elapsed. The following code example uses setTimeout() with a self-executing anonymous function.
|
1 2 3 4 5 6 7 8 |
const x = 2; // 2 seconds (function() { // do some work console.log(`Pausing for ${x} seconds…`); setTimeout(arguments.callee, x * 1000); })(); |
The above code uses arguments.callee() to get the anonymous function’s name. ES5 forbids the use of arguments.callee() and suggest giving the function expressions a name:
|
1 2 3 4 5 6 7 8 9 10 11 |
const x = 2; // 2 seconds fun = function() { // do some work console.log(`Pausing for ${x} seconds…`); // work ends setTimeout(fun, x * 1000); } fun(); |
That’s all about repeatedly call a function in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)