JavaScript 手写setTimeout


let setTimeout = (sec, num) => {
  // 初始当前时间
  const now = new Date().getTime()
  let flag = true
  let count = 0
  while (flag) {
    count++
    // 再次运行时获取当前时间
    const after = new Date().getTime()
    // 需要等待的时间
    const dealy = sec * 1000
    // 当前运行时间 - 初始当前时间 >= 等待时间 ===>> 跳出
    if (after - now >= dealy) {
      flag = false
    } else {
      console.info('count', count)
    }
  }
  return new Promise((resolve, reject) => {
    resolve(num * num)
  })
}

let result = ''
const res = setTimeout(3, 10)
console.info(res) // Promise { 100 }
// 返回的是一个promise,promise中resolve中的值需要在then中拿到
res.then(x => {
  result = x
  console.info(result) // 100
})


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM