The JavaScript Window setTimeout() method is used to execute a specified function after a specified delay. It takes two arguments: the function to be executed, and the delay (in milliseconds) before the function should be executed. It returns a unique identifier that can be used to cancel the timeout later.
Here are some examples of how the setTimeout() method can be used in JavaScript code:
- To execute a function after a specified delay, you can use the following code:
// define the function to be executed
function myFunction() {
// code to be executed
}
// execute the function after 1000 milliseconds (1 second)
var timeout = setTimeout(myFunction, 1000);
- To cancel the timeout, you can use the identifier returned by the setTimeout() method as follows:
// cancel the timeout
clearTimeout(timeout);
- To execute a function after a specified delay and then execute it repeatedly at a specified interval, you can use the following code:
// define the function to be executed
function myFunction() {
// code to be executed
// schedule the next execution of the function
timeout = setTimeout(myFunction, 1000);
}
// execute the function after 1000 milliseconds (1 second)
var timeout = setTimeout(myFunction, 1000);
Overall, the setTimeout() method provides a convenient way to execute a function after a specified delay. It can be useful for tasks such as displaying a message or other element on a page after a certain amount of time, or for other operations that require delaying the execution of a function.
Leave a Reply