javascript异步例子

例子1:

//callback 异步回调
setTimeout(function() {
    
    
console.log('World');
}, 1000);
console.log('Hello');
setTimeout(function() {
    
    
console.log(1);
setTimeout(function() {
    
    
console.log(2);
}, 1000);
}, 1000);

在这里插入图片描述
如果在Chrome浏览器开发者工具控制台运行,中间的数字 14363 是一个计时器 ID。当使用 setTimeout 或 setInterval 时,JavaScript 引擎会返回一个唯一的 ID,这个 ID 可以用来取消定时器。例如,可以使用 clearTimeout 或 clearInterval 来取消定时器。

在代码中,调用 setTimeout 两次,每次都会返回一个定时器 ID。这个 ID 并不具有特别的意义,只是表示 JavaScript 引擎内部生成的一个唯一标识符。

如果在VS Code中运行,就不会有这个数字。
在这里插入图片描述

例子2:

// 定义一个异步函数,返回一个经过指定时间后解决的 Promise
function timeout(time) {
    
    
  return new Promise(function(resolve) {
    
    
    setTimeout(resolve, time);
  });
}

// 确保这段代码在异步函数中执行
async function main() {
    
    
  await timeout(1000); // 等待1秒
  console.log(1);      // 1秒后打印 1

  await timeout(1000); // 再等待1秒
  console.log(2);      // 又1秒后打印 2
}

// 调用 main 函数
main();

在这里插入图片描述

例子3:

async function timeout(time) {
    
    
    return new Promise(function(resolve) {
    
    
      setTimeout(resolve, time);
    });
  }
  
  await timeout(1000);
  console.log(1);
  await timeout(1000);
  console.log(2);
  

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42465759/article/details/140420379