The setTimeout function is used to perform an action after a specified amount of time. This is useful when you want to perform a task after a waiting period.
The syntax of the setTimeout function is as follows:
setTimeout(function, milliseconds, param1, param2, ...)
Where:
Let's see a simple example to understand how to use setTimeout in JavaScript:
function sayHello() {
console.log("Xin chà o!");
}
setTimeout(sayHello, 3000);
In the example above, we declare a function called sayHello to print the message 'Hello!' to the console. Then, we use setTimeout to call this function after 3000 milliseconds (equivalent to 3 seconds). When the waiting time is over, the sayHello function will be executed and the message 'Hello!' will be displayed on the console.
You can also use parameters in the function called by setTimeout. Here is an example:
function greet(name) {
console.log("Xin chà o, " + name + "!");
}
setTimeout(greet, 2000, "John");
In this example, we declare a function greet that takes a parameter name. This function will print the message "Hello, " concatenated with the passed-in name. By using setTimeout with the parameter "John" and a wait time of 2000 milliseconds (equivalent to 2 seconds), the greet function will be called and the message "Hello, John!" will be displayed on the console after 2 seconds.
To stop a setTimeout function that is counting down, you can use the clearTimeout function. You need to store the ID of the timeout created by calling setTimeout and then pass this ID to the clearTimeout function to stop the countdown. Here is an example:
function sayHello() {
console.log("Xin chà o!");
}
var timeoutId = setTimeout(sayHello, 3000);
// Ngừng timeout sau 2 giây
setTimeout(function() {
clearTimeout(timeoutId);
}, 2000);