63

Function sleep in JavaScript

 4 years ago
source link: https://www.tuicool.com/articles/eIrmeiR
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In Java, Thread.sleep causes the current thread to suspend execution for a specified period.

This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. However, JavaScript does NOT have such a native implementation. Thanks to async function , we can emulate the behavior:

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

Use case: print number 1 to 5 per second in consecutive way.

Async & Await implementation

async function one2FiveInAsync() {
  for(let i = 1; i <= 5; i++) {
    console.log(i);
    await sleep(1000)
  }
}

one2FiveInAsync();

Promise implementation

function one2FiveInPromise() {
  function logAndSleep(i) {
    console.log(i);
    if (i === 5) {
      return;
    }
    return sleep(1000).then(() => logAndSleep(i + 1));
  }

  logAndSleep(1);
}

one2FiveInPromise();

Notice

  • If you want to follow the latest news/articles for the series of my blogs, Please 「Watch」 to Subscribe.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK