setTimeout() method
A built-in JavaScript function called setTimeout allows you to run a function or evaluate an expression after a predetermined millisecond delay. It requires two parameters: the code or function to be evaluated and the delay before execution.
Syntax:
setTimeout(function, delay);
- function: This parameter specifies the function to be executed or the code to be evaluated after the delay.
- delay: This parameter specifies the time delay in milliseconds before the function is executed.
Example: The below code explains the basic use of the setTimeout method to execute a callback function after some delay.
<!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 setTimeout
</h2>
<h3>
Click below button to increase count
value<br /> after one second
</h3>
<button id="myButton">
Click me
</button>
<h4 id="result">
Count: 0
</h4>
<script>
const myBtn = document.getElementById('myButton');
let count = 0;
myBtn.addEventListener('click', function () {
const result = document.getElementById('result');
let intervalId = setTimeout(() => {
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.