How can i make this code run asynchronously without using setTimeout

57 views Asked by At
const delayFunction = async () => {
  const startTime = new Date().getTime();

  const duration = 10000; 

  console.log('START')
  while (new Date().getTime() - startTime < duration) {
   // this loop runs for 10 seconds
  }
  console.log('STOP');
};

const starterFunction = async () => {
  console.log('1');
  delayFunction();
  console.log('2');
  return 'DONE'
};

console.log(starterFunction())

so now I want an output as below:

1

2

DONE

START

STOP

If anyone knows how to achieve this with asynchronous programming please help me with this.

I tried creating a new promise and tried to execute the code inside it but even that dosent seem to be working.

const delayFunction = async () => {
  return new Promise((resolve,reject) => {
     const startTime = new Date().getTime();

     const duration = 10000; 

     console.log('START')
     while (new Date().getTime() - startTime < duration) {
     // this loop runs for 10 seconds
     }
     resolve(console.log('STOP'));
  });
};
1

There are 1 answers

0
Owali Ullah Shawon On
  const duration = 10000;

  console.log('START');

  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('STOP');
      resolve();
    }, duration);
  });
};

const starterFunction = async () => {
  console.log('1');
  console.log('2');
  await delayFunction();
  return 'DONE';
};

(async () => {
  await starterFunction();
})();