JavaScript/sleep

来自康健生活
Kangkk​(留言 | 贡献)2020年6月24日 (三) 16:59的版本 (→co)

引用

模拟

es5

模板:Leftrightflex

进程阻塞、性能和负载问题

es6

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}
sleep(500).then(() => {
  // ...
})

模板:Leftrightflex

同步执行 模板:Leftrightflex

模板:Leftrightflex

(来源摘自互联网示例,作者 未知)

co

function sleep(ms) {
  return function (cb) {
    setTimeout(cb, ms);
  }
}
co(function *() {
  var now = Date.now();
  yield sleep(2000);
  expect(Date.now() - now).to.not.be.below(2000);
});