0

I expect page loading to be finished at second 2 and at second 4, in console.log we should see another text. but the code is synchronous, not asynchronous. so page loading will finish after 4 seconds.

const sleep = (millisecond = 1000) => {
  return new Promise((resolve, reject) => {
    const date = Date.now();
    while (Date.now() - date < millisecond) {}
    console.log(millisecond + ' sleep finished ' + Date.now());
  });
};

sleep(2000).then();

async function asyncFunc() {
  sleep(2000);
};

asyncFunc().then();
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    You're using a busy loop to sleep - which is inherently a synchronous operation. If you want to sleep asynchronously, use `setTimeout`. – SuperStormer Jul 21 '21 at 20:08
  • A busy while loop will make the UI unresponsive and will cause the JS engine to be stopped by the browser. – Ruan Mendes Jul 21 '21 at 20:11
  • In your code I see some fundamental misunderstandings on basic principles of how JavaScript works. You should probably read some introductional tutorial about js in general and promises and async programming in detail – derpirscher Jul 21 '21 at 20:14
  • I've a gut feeling you believe JS is multi-threaded and async is like spawning another thread, unfortunately not. Your maybe mixing it with something like Rust & tokio with it's spawn_blocking & it's async (futures) / await. – Keith Jul 21 '21 at 20:14

0 Answers0