延时

在JavaScript中,延时函数主要用于在执行某些操作后设置一个延迟,以便在指定的时间后执行另一个操作。以下是JavaScript中常用的延时函数:

  1. setTimeout() setTimeout() 函数用于在指定的毫秒数后执行一个函数或计算一个表达式。它返回一个定时器ID,可以用来取消定时器。

    1// 延迟1000毫秒(1秒)后执行函数
    2setTimeout(function() {
    3  console.log('Hello, World!');
    4}, 1000);

    你也可以使用箭头函数来简化写法:

    1setTimeout(() => {
    2  console.log('Hello, World!');
    3}, 1000);
  2. setInterval() setInterval() 函数用于重复执行一个函数或计算一个表达式,每隔指定的毫秒数执行一次。它也返回一个定时器ID,可以用来取消间隔。

    1// 每隔1000毫秒(1秒)执行一次函数
    2setInterval(function() {
    3  console.log('Hello, World!');
    4}, 1000);

    同样,可以使用箭头函数:

    1setInterval(() => {
    2  console.log('Hello, World!');
    3}, 1000);
  3. clearTimeout() clearTimeout() 函数用于取消由 setTimeout() 设置的定时器。你需要传递之前 setTimeout() 返回的定时器ID。

    1const timerId = setTimeout(() => {
    2  console.log('This will not be printed');
    3}, 1000);
    4
    5// 在1000毫秒之前调用clearTimeout
    6clearTimeout(timerId);
  4. clearInterval() clearInterval() 函数用于取消由 setInterval() 设置的重复执行的定时器。同样,你需要传递之前 setInterval() 返回的定时器ID。

    1const intervalId = setInterval(() => {
    2  console.log('This will be printed until clearInterval is called');
    3}, 1000);
    4
    5// 调用clearInterval来停止重复执行
    6clearInterval(intervalId);
  5. Promiseasync/await 与延时 如果你在使用现代JavaScript,特别是当你使用 Promiseasync/await 时,你可以创建自定义的延时函数:

     1function delay(ms) {
     2  return new Promise(resolve => setTimeout(resolve, ms));
     3}
     4
     5// 使用async/await
     6async function printWithDelay() {
     7  console.log('Hello, World!');
     8  await delay(1000);
     9  console.log('This was delayed by 1 second');
    10}
    11
    12printWithDelay();

这些延时函数在JavaScript中非常有用,尤其是在处理异步操作、动画、用户界面更新等场景中。