例子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);