The difference between setinterval and settimeout

The difference between setinterval and settimeout

  1. The execution time interval is different: setInterval will execute the specified function every once in a while according to the specified time interval, and setTimeout will only execute the specified function once after the specified time interval.
  2. Whether to execute repeatedly: setInterval will always execute the specified function repeatedly according to the specified time interval until clearInterval is called to stop its execution; while setTimeout will only execute the specified function once, unless setTimeout is called again after the function is executed.
  3. The return value is different: setInterval returns an ID that uniquely identifies the timer, and the execution of the timer can be stopped by calling the clearInterval function; while setTimeout returns an ID that uniquely identifies the timer, and the execution of the timer can be stopped by calling the clearTimeout function.

Here is an example of JavaScript code using setInterval and setTimeout:

// 使用 setInterval 定时执行函数
let intervalId = setInterval(function() {
    
    
  console.log('setInterval: Hello world!');
}, 1000);

// 使用 setTimeout 定时执行函数
let timeoutId = setTimeout(function() {
    
    
  console.log('setTimeout: Hello world!');
}, 2000);

// 停止定时器的执行
clearInterval(intervalId);
clearTimeout(timeoutId);

In this example, we use setInterval and setTimeout to execute a function regularly, where the time interval of setInterval is 1 second, and the time interval of setTimeout is 2 seconds. Then we stop their execution with clearInterval and clearTimeout respectively. Note that we need to save the returned timer ID in order to call the corresponding clear function later.

Guess you like

Origin blog.csdn.net/liu511623/article/details/129978024