
212 views
JavaScript setTimeout() method
The setTimeout()
method in JavaScript is used to schedule the execution of a function or the evaluation of an expression after a specified delay (in milliseconds). It is a way to introduce a time delay in your code. Here’s the syntax:
JavaScript
setTimeout(function, delay, param1, param2, ...)
function
: The function to be executed after the delay. This can be either a function reference or an anonymous function.delay
: The delay (in milliseconds) after which the function should be executed.param1, param2, ...
(optional): Additional parameters to be passed to the function.
Here’s an example that demonstrates the usage of setTimeout()
:
JavaScript
function greet(name) {
console.log("Hello, " + name + "!");
}
setTimeout(greet, 2000, "John");
In this example, the greet()
function will be executed after a delay of 2000 milliseconds (2 seconds), and it will print “Hello, John!” to the console.
Note that you can also use an anonymous function as the first parameter of setTimeout()
:
JavaScript
setTimeout(function() {
console.log("Delayed function executed");
}, 3000);
In this case, the anonymous function will be executed after a delay of 3000 milliseconds (3 seconds).