在 javascript 的另一个 setTimeout 函数中使用 setTimeout

Use setTimeout inside another setTimeout function in javascript

我有这个代码:-

    var i = 3
    var p = Promise.resolve(i)
    while (i > 0) {
      (i => {
        p = p.then(() => {
          return new Promise(function (resolve, reject) {
            console.log('start', i)        
            setTimeout(function () {
              setTimeout(() => {
                console.log('timeout')
              }, 1000);
              console.log('end', i)
              resolve()
            }, 1000)
          })
        })
      })(i)
      i--
    }
    p = p.then(data => console.log('execution ends'))

我得到了这样的输出:-

start 3
end 3
start 2
timeout
end 2
start 1
timeout
end 1
execution ends
timeout

但是,我的预期输出应该是这样的:-

start3
timeout
end3
start2
timeout
end2
start1
timeout
end1

简而言之,正如我预期的输出 'timeout' 日志应该每 2 秒打印一次,其他日志应该每 1 秒打印一次。

试试这个:

var i = 3
var p = Promise.resolve(i)
while (i > 0) {
  (i => {
    p = p.then(() => {
      return new Promise((resolve) => {
        console.log('start', i)
        setTimeout(() => {
          return new Promise((resolve) => {
            setTimeout(() => {
           console.log('timeout')
             resolve()
            }, 1000)
          }).then(() => {
           console.log('end', i)
           resolve()
          })
        }, 1000)
      })
    })
  })(i)
  i--
}
p = p.then(data => console.log('execution ends'))

我所做的是将一个新的 Promise 添加到一个新的日志记录超时 timeout 所以它只会在完成后继续。

下面的做法正确吗?

const later = time => value =>
  new Promise(
    resolve=>
      setTimeout(() => {
        resolve(value)
      }, time)
  );
const afterOneSecond = later(1000);
Array.from(new Array(3),(i,index)=>3-index)
.reduce(
  (promise,value)=>
    promise.then(afterOneSecond)
    .then(()=>console.log("start:",value))
    .then(afterOneSecond)
    .then(()=>console.log("timeout"))
    .then(()=>console.log("end:",value)),
  Promise.resolve()
)
.then(() => console.log('execution ends'));