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 函数 #13

Open
nmsn opened this issue Nov 18, 2022 · 1 comment
Open

实现 sleep 函数 #13

nmsn opened this issue Nov 18, 2022 · 1 comment

Comments

@nmsn
Copy link
Contributor

nmsn commented Nov 18, 2022

休眠/暂停固定时间后,执行后续逻辑

function sleep(time) {

}

// ---

console.log('now')
sleep(1000)
console.log('after 1 second')
@nmsn
Copy link
Contributor Author

nmsn commented Nov 18, 2022

同步执行

function sleep(delay) {
  const  start = (new Date()).getTime();
  while ((new Date()).getTime() - start < delay) {
    continue;
  }
}

// ---

console.log(1);
sleep(1000);
console.log(2);

异步执行

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

// ---

async function a() {
    console.log(1);
    await sleep(1000);
    console.log(2);
}

a();

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