Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

4 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


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.


How to use


The syntax of the setTimeout function is as follows:

setTimeout(function, milliseconds, param1, param2, ...)






Where:


Example


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.


Using parameters


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.


Stop SetTimeOut


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);








Read more
On This Page