【问题标题】:Use setTimeout inside another setTimeout function in javascript在 javascript 的另一个 setTimeout 函数中使用 setTimeout
【发布时间】:2018-09-22 13:25:53
【问题描述】:

我有这个代码:-

    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

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

【问题讨论】:

  • 你可以在你的预期输出中添加时间。我不清楚间隔。看到第一个演示中的时间戳?
  • 你的问题有点不清楚。此外 * 我的预期输出看起来像 * 与当前代码的输出相同。请检查并更新问题以获得更清晰的信息

标签: javascript node.js socket.io mean-stack async.js


【解决方案1】:

以下操作是否正确?

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'));

【讨论】:

    【解决方案2】:

    试试这个:

    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 的新超时中,这样它只会在完成后继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多