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

实0087 现一个 sleep 函数? #87

Open
lotosv2010 opened this issue Sep 6, 2019 · 0 comments
Open

实0087 现一个 sleep 函数? #87

lotosv2010 opened this issue Sep 6, 2019 · 0 comments
Labels
interview 面试题 JavaScript JavaScript系列

Comments

@lotosv2010
Copy link
Owner

lotosv2010 commented Sep 6, 2019

1. Promise

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

2. Generator

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

3. 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();

4. ES5

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

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

5. 参考

【ECMAScript6】es6 要点(二)Promise | 自个写一个Promise | Generator | Async/Await

@lotosv2010 lotosv2010 added JavaScript JavaScript系列 interview 面试题 labels Sep 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
interview 面试题 JavaScript JavaScript系列
Projects
None yet
Development

No branches or pull requests

1 participant