📜  js settimeout - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:59.387000             🧑  作者: Mango

JS setTimeout

The JavaScript setTimeout method is a function that allows you to execute a piece of code after a specified amount of time has passed. It is often used in client-side scripting to create animations, perform background tasks, or delay the execution of code until a certain event has occurred.

Syntax

The setTimeout method takes two arguments:

setTimeout(function, delay);
  • function: The function to be executed after the specified delay.
  • delay: The time delay in milliseconds before the function is executed.
Example
function showMessage() {
  console.log("Hello, World!");
}

setTimeout(showMessage, 3000);

In this example, the showMessage function is executed after a delay of 3000 milliseconds (or 3 seconds).

Cancelling setTimeout

You can cancel a setTimeout function before it is executed by calling the clearTimeout method and passing in the setTimeout ID value as an argument:

var myTimeout = setTimeout(function() {
  console.log("This message will not be displayed.");
}, 2000);

clearTimeout(myTimeout);

In this example, the setTimeout function is cancelled before the message is displayed.

Conclusion

The JavaScript setTimeout method is a useful tool for creating time-delayed functions in client-side scripting. It is simple to use and can be cancelled at any time using the clearTimeout method.