为什么在这个例子中脚本首先嵌入回调 运行?

Why does the script embedded in the callback run first in this example?

我想了解为什么在这种特定情况下首先弹出 script2 的警报?如果我在基本函数声明中取消对 setTimeout 的注释,script1 将首先发出警报。 我期望无论有没有 setTimeout,在基本函数中,script1 都会首先发出警报。一个澄清的答案将不胜感激。

function base(src, cb) {
  //setTimeout(() => {
  cb();
  alert(src + ' finished executing')
  //}, 100)
}

function first() {
  setTimeout(() => {
    alert('first');
  }, 110)
}

function second() {
  setTimeout(() => {
    alert('second');
  }, 110);
}

base('script 1', () => {
  first();
  base('script 2', () => {
    second();
  });
})

您的代码调用 base() 函数,传入一个也调用 base() 的函数。因此 "second" 函数首先完成,因为对 base() 的嵌套调用在它为 "first" 函数发布 alert() 之前调用它。

使用 console.log() 而不是 alert()

函数first()先于second()执行,但是alert是在执行完之后才产生的,因为你把这两个都封装到了回调方法中。并在完成整个功能后生成警报。也许您应该按照以下方式编写代码以了解发生了什么。

function base(src, cb) {
  //setTimeout(() => {
  cb();
  alert(src + ' finished executing')
  //}, 100)
}

function first() {
  setTimeout(() => {
    alert('first');
  }, 110)
}

function second() {
  setTimeout(() => {
    alert('second');
  }, 110);
}

base('script 1 and script 2', () => {
  base('script 1', () => {
    first();
  });
  base('script 2', () => {
    second();
  });
})