How to use setTimeout In Javascript
setTimeout is a function in JavaScript used to execute a piece of code or a function after a specified delay. It allows you to execute a function only once after a certain amount of time has passed.
Syntax:
setTimeout(function, delay);
Example: Printing the output “Hello World!” after 2 seconds of code execution.
function greet() {
console.log("Hello, world!");
}
// Executes greet function after 2 seconds
setTimeout(greet, 2000);
Output:
Difference Between setTimeout & setInterval in JavaScript
JavaScript has both setTimeout and setInterval functions that are used for executing code after a certain delay. However, they differ in how they handle the timing of execution. Understanding their differences is crucial for effectively managing asynchronous operations in our code which is explained below:
Table of Content
- Using setTimeout
- Using setInterval
- Difference between setTimeout and setInterval