Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 sleep 函数 #15

Open
sihai00 opened this issue Jul 29, 2019 · 0 comments
Open

实现 sleep 函数 #15

sihai00 opened this issue Jul 29, 2019 · 0 comments
Assignees

Comments

@sihai00
Copy link
Owner

sihai00 commented Jul 29, 2019

sleep函数

延时函数:等待一段时间,再继续进行

  1. Promise
  2. Generator
  3. async
  4. es5

Promise

//Promise
const sleep = time => {
  return new Promise(resolve => setTimeout(resolve,time))
}
sleep(1000).then(()=>{
  console.log(1)
})

Generator

//Generator
function* sleepGenerator(time) {
  yield new Promise(function(resolve,reject){
    setTimeout(resolve,time);
  })
}
sleepGenerator(1000).next().value.then(()=>{console.log(1)})

async

//async
function sleep(time) {
  return new Promise(resolve => setTimeout(resolve,time))
}
async function output() {
  let out = await sleep(1000);
  console.log(1);
  return out;
}
output();

es5

//ES5
function sleep(callback,time) {
  if(typeof callback === 'function')
    setTimeout(callback,time)
}

function output(){
  console.log(1);
}
sleep(output,1000);

参考

实现一个 sleep 函数

@sihai00 sihai00 self-assigned this Jul 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant