Skip to content

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

The setInterval() method in JavaScript can be used to perform periodic (in milliseconds) evaluation of expressions or call a JavaScript function. 

The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

1 second = 1000 milliseconds.

setInterval(function, milliseconds, param1, param2, ...)

Parameters: This function accepts the following parameters:  

  • function: This parameter holds the function name which is to be called periodically.
  • milliseconds: This parameter holds the period, in milliseconds, setInterval() calls/executes the function above.
  • param1, param2, …: Some additional parameters to be passed as input parameters to function.

Return Value: The id of the timer. Use this id with clearInterval() to cancel the timer.

<!DOCTYPE html>
<html>

<head>
	<title>
		How to call a function
		repeatedly every 5
		seconds in JavaScript ?
	</title>
</head>

<body>
	

<p>
		Click the button to start
		timer, you will be alerted
		every 5 seconds until you
		close the window or press
		the button to stop timer
	</p>


	
	<button onclick="startTimer()">
		Start Timer
	</button>
	
	<button onclick="stopTimer()">
		Stop Timer
	</button>
	
	<script>
		var timer;
		
		function startTimer() {
			timer = setInterval(function() {
				alert("5 seconds are up");
			}, 5000);
		}
		
		function stopTimer() {
			alert("Timer stopped");
			clearInterval(timer);
		}
	</script>
</body>

</html>
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments