To call a function repeatedly after every 5 seconds in JavaScript, you can use the built-in setInterval()
method.
The setInterval()
method calls a function repeatedly after a specified time interval. It keeps calling the function until it is explicitly stopped using the clearInterval()
method.
Here is the syntax of the setInterval() method:
setInterval(function, interval, param1, param2);
Here, function
is the function name that is to be called repeatedly. interval
is the time in milliseconds after which the function should be called repeatedly.
And param1
, param2
are the optional parameters that can be used to pass some additional information to the setInterval()
method.
See the below implementation where the function myFunction()
gets called after every 5 seconds:
Example:
var timerId = setInterval(myFunction, 5000); function myFunction(){ // Writes Hello world after every 5 seconds. document.write('Hello world!<br>'); // Write your stuff here }
The setInterval() method in the above example keeps calling the function myFunction() infinitely after every 5 seconds. That is, it never stops.
If you want to stop its execution, you can use the clearInterval()
method. The clearInterval() method needs a parameter which is the Id of the setInterval() method which we stored in the timerId
variable in the above example.
clearInterval(intervalId);
The clearInterval() method in the following example clears the setInterval() method once the counter
variable reaches 5:
Example:
var timerId = setInterval(myFunction, 1000); var counter = 0; function myFunction(){ // Writes Hello world after every 5 seconds. document.write('Hello world!<br>'); counter = counter + 1; if(counter>=5){ // Clear setInterval() method clearInterval(timerId); document.write('Timer stopped'); } // Write your stuff here }
Thanks for reading.