setInterval() method
Another built-in JavaScript function that allows you to run a function or evaluate an expression repeatedly at certain time interval. It also takes same two parameters.
Syntax:
setInterval(function, interval);
- function: This parameter specifies the function to be executed or the code to be evaluated at each interval.
- interval: This parameter specifies the time interval in milliseconds between each execution of the function.
Example: The below code implements the setInterval method with a basic example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="text-align: center;">
<h2>
JavaScript setInterval
</h2>
<h3>
The below count value will increase
<br /> automatically after evry one second.
</h3>
<h4 id="result">
Count: 0
</h4>
<script>
let count = 0;
const result = document.getElementById('result');
let intervalId = setInterval(() => {
count++;
result.innerHTML = `Count: ${count}`;
}, 1000);
</script>
</body>
</html>
Output:
Difference Between setTimeout & setInterval
JavaScript provides two essential functions: setTimeout and setInterval. While both serve similar purposes, they have distinct differences that developers should be aware of to effectively manage timing-related tasks in their code.