In JavaScript, the setTimeout() function is used to schedule the execution of a function after a specified delay. It allows you to introduce a delay in the execution of code, creating a timed event.
The basic syntax of the setTimeout() function is as follows:
setTimeout(function, delay);
The parameters are:
function: The function to be executed after the specified delay.
delay: The delay (in milliseconds) before the execution of the function.
Here's an example that demonstrates the usage of setTimeout():
function greet() {
console.log("Hello, world!");
}
setTimeout(greet, 2000); // Executes the greet() function after a 2000ms (2 seconds) delay
In the example above, the greet() function is scheduled to be executed after a delay of 2000 milliseconds (2 seconds). When the specified delay has passed, the function will be called, and the message "Hello, world!" will be logged to the console.
You can also pass arguments to the function being called using setTimeout(). Here's an example:
function greet(name) {
console.log("Hello, " + name + "!");
}
setTimeout(greet, 2000, "John"); // Executes the greet() function with the argument "John" after a 2000ms delay
In this case, the greet() function is called after a delay of 2000 milliseconds, and the argument "John" is passed to the function. The message "Hello, John!" will be logged to the console.
The setTimeout() function is commonly used in JavaScript for various purposes, such as delaying animations, creating timeouts for asynchronous operations, or scheduling periodic tasks using recursive setTimeout() calls. It provides a way to introduce delays and timed events in your code, adding flexibility and control to your applications.