一起手写吧!sleep函数!

Posted magicg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一起手写吧!sleep函数!相关的知识,希望对你有一定的参考价值。

Async/Await 版本

function sleep(delay) {
  return new Promise(reslove => {
    setTimeout(reslove, delay)
  })
}

!async function test() {
  const t1 = +new Date()
  await sleep(3000)
  const t2 = +new Date()
  console.log(t2 - t1)
}()

 

更优雅的写法

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

// 用法
sleep(500).then(() => {
    // 这里写sleep之后需要去做的事情
})

 

开源的力量

const sleep = require("sleep")

const t1 = +new Date()
sleep.msleep(3000)
const t2 = +new Date()
console.log(t2 - t1)

优点:能够实现更加精细的时间精确度,而且看起来就是真的 sleep 函数,清晰直白。

缺点:缺点需要安装这个模块,^_^,这也许算不上什么缺点。

 

以上是关于一起手写吧!sleep函数!的主要内容,如果未能解决你的问题,请参考以下文章

手写数字识别——基于全连接层和MNIST数据集

一起手写吧!ES5和ES6的继承机制!

前端面试题之手写promise

Sleep() 方法后的代码片段没有被执行

手写dubbo-7手撸了自定义协议远程调用服务动态扩容,梳理一下吧!

关于代码手写UI,xib和StoryBoard