简体   繁体   中英

Which way is more convenient execute an async function in endless loop with a sleep between each execution (Node.js / Vanilla JS)

I wrote some asynchronous function which does something and then returns nothing. After the function has ended its execution I want to wait a few seconds and then go over the same routine.

The flow goes like this: 1. Execute the function 2. Wait until the execution is done 3. Wait/Sleep for some interval 4. Start over from step 1

An endless loop of function execution, sleep and start over again.

Now my question is which of the 2 code blocks below is more appropriate to use:

Option 1:

const MEANING_OF_LIFE = 42;
const DELAY_IN_MILLISECONDS = 1000;


const whatsTheMeaningOfLife = async () => {
  console.log(MEANING_OF_LIFE);
}

const outter = fn => {

  inner = async fn => {
    await fn();
    setTimeout(() => outter(fn), DELAY_IN_MILLISECONDS);
  };

  inner(fn);
};

(() => {
  outter(whatsTheMeaningOfLife);
})();

Option 2:

const MEANING_OF_LIFE = 42;
const DELAY_IN_MILLISECONDS = 1000;


const whatsTheMeaningOfLife = () => {
  console.log(MEANING_OF_LIFE);
}

const sleep = () => {
  return new Promise((resolve, ) => {
    setTimeout(() => resolve(), DELAY_IN_MILLISECONDS);
  });
};

(async () => {
  while(true) {
    await whatsTheMeaningOfLife();
    await sleep();
  }
})();

The second version seems shorter, much cleaner, more understandable and also allows you to properly handle errors. I would however recommend to pass the DELAY_IN_MILLISECONDS as an argument to sleep , not use a global constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM