Categories
JavaScript Answers

How to get return value from setTimeout with JavaScript?

Spread the love

To get return value from setTimeout with JavaScript, we can create a promise from the setTimeout code.

For instance, we write

const x = () => {
  const promise = new Promise((resolve, reject) => {
    window.setTimeout(() => {
      resolve("done!");
    });
  });
  return promise;
};

const y = async () => {
  const result = await x();
  console.log(result);
};

to define function x that returns a promise created with the Promise constructor.

We call it with a callback that calls setTimeout with a callback that calls resolve to return the resolve value of the promise.

Then we return the promise.

Next, we define function y that calls x and gets the resolved value with await.

Therefore, result is 'done!'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.