Skip to content
大纲

实现一个 sleep

sleep 函数作用是让线程休眠,等到指定时间在重新唤起。

思考可从 Promise, Generator, Async/Await 等角度实现

js
// 简单实现
const sleep = (...rest) =>
  new Promise((resolve, reject) => setTimeout(resolve, ...rest))

// testing
sleep(1000, 'hello').then((res) => console.log(res))

// 补充结构
const sleep = (...rest) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(msg)
    }, ...rest)
  })
}
js
function* sleepGenerator(time) {
  yield new Promise((resolve, reject) => {
    setTimeout(resolve, time)
  })
}

sleepGenerator(1000)
  .next()
  .value.then((res) => {
    console.log(res)
  })
js
// 同 promise,仅使用时为 async
const sleep = (...rest) =>
  new Promise((resolve, reject) => setTimeout(resolve, ...rest))

async function init() {
  const res = await sleep(1000, 'async run')
  console.log(res)
}
init()
js
function sleep(callback, time, msg) {
  if (typeof callback === 'function') {
    setTimeout(callback, time, msg)
  }
}

sleep(console.log, 1000, 'es5 sleep')