Detailed usage of setTimeout() function in JavaScript

1 Basic grammar

setTimeout()A function is a timer function in JavaScript that allows us to execute specified code after a certain time interval. Its basic syntax is as follows:

setTimeout(callback, delay, arg1, arg2, ...)

Among them, the callback parameter is a function that will be executed after the specified delay time. The delay parameter is a time value in milliseconds specifying the delay time. You can also optionally pass some parameters to the callback function.

2 calling method

setTimeout()The function is called as follows:

let timerId = setTimeout(callback, delay, arg1, arg2, ...);

2.1 Calling method without passing parameters

function sayHello() {
    
    
  console.log('Hello');
}
setTimeout(sayHello, 1000);

In this example, we define a function called sayHello and use setTimeout()the function to delay its execution after 1 second. When 1 second has elapsed, the console will output "Hello".

2.2 Calling method of parameter passing

Sample code:

function sayHelloSth(name) {
    
    
  console.log(`Hello ${
      
      name}!`);
}

// 在 3 秒后打印 "Hello World!"
setTimeout(sayHelloSth, 3000, 'World');

In the sample code above, we defined a sayHelloSth()function, which takes one parameter name. Then, use setTimeout()the function to call sayHelloSth()the function and specify a delay of 3 seconds. We also pass the string "World" as the third parameter to setTimeout()the function so that it can be passed to sayHelloSth()the function. Therefore, after 3 seconds, you will see the output "Hello World!" on the console.

3 cancel delayed execution

When setTimeout()the function is called, it immediately returns a unique timer ID, which we can use to cancel delayed execution. For example:

let timerId = setTimeout(function() {
    
    
  console.log('This message will never be displayed');
}, 5000);

clearTimeout(timerId);

In this example, we use the setTimeout function to create a timer and assign it to timerIda variable. Then, we immediately use setTimeout()the function to cancel the timer. This means that after 5 seconds, no messages will be output to the console.

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/131001815