jQuery's `setTimeout()` function allows you to **call** a function after a specified delay. This is particularly useful for tasks such as:
The `setTimeout()` function follows a simple syntax in jQuery:
setTimeout(function() { // code //}, delayInMilliseconds);
Let's break down the components:
Let's say you want to **call** a function called `showGreeting()` after a 2-second delay:
setTimeout(function() {
showGreeting();
}, 2000); // 2000 milliseconds = 2 seconds
function showGreeting() {
alert("Hello, world!");
}
In this example, the `setTimeout()` function will **call** the `showGreeting()` function after 2 seconds. The `showGreeting()` function, in turn, will display an alert box with the message "Hello, world!".
You can also use `setTimeout()` with anonymous functions, which are functions defined directly within the `setTimeout()` call:
setTimeout(function() {
console.log("This message will appear after 1 second");
}, 1000); // 1000 milliseconds = 1 second
In this example, an anonymous function is defined within the `setTimeout()` call. This function simply logs a message to the console after a delay of 1 second.
If you need to cancel the execution of a `setTimeout()` function before it has completed, you can use the `clearTimeout()` function.
var timeoutId = setTimeout(function() {
console.log("This message might not appear");
}, 5000); // 5000 milliseconds = 5 seconds
// After a shorter delay, clear the timeout
setTimeout(function() {
clearTimeout(timeoutId);
}, 2000); // 2000 milliseconds = 2 seconds
In this code, `setTimeout()` is used to set a delay of 5 seconds before logging a message. However, another `setTimeout()` is used to **call** `clearTimeout()` after 2 seconds. This will cancel the original `setTimeout()` function, preventing the message from being logged.
Ask anything...