Home >Web Front-end >JS Tutorial >How to Create and Manage Promises Using setTimeout in JavaScript?

How to Create and Manage Promises Using setTimeout in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 00:27:11711browse

How to Create and Manage Promises Using setTimeout in JavaScript?

How to Create a Promise from setTimeout

Creating a Basic Promise for setTimeout

To create a promise that async can return after the setTimeout callback fires, we can wrap the setTimeout function within a promise constructor, as seen in the snippet below:

<br>function setTimeoutReturnPromise(delay) {<br>  return new Promise((resolve) => {</p>
<pre class="brush:php;toolbar:false">setTimeout(resolve, delay);

});
}

This function takes a delay as an argument and returns a promise. The promise will resolve after the specified delay has elapsed, and the setTimeout function's callback will be executed.

Using the Promise with async

Now, our async function can use the setTimeoutReturnPromise function to create a promise that it can return. This allows us to use the then() method to execute code after the setTimeout callback has been invoked:

<br>async(function() {<br>  setTimeoutReturnPromise(5000).then(() => {</p>
<pre class="brush:php;toolbar:false">console.log("async called back");

});
});

Updating for ES2015 and Beyond

Since the introduction of ES2015 and modern JavaScript, promises have become built-in features. The syntax has been simplified, as shown below:

<br>function later(delay) {<br>  return new Promise((resolve) => {</p>
<pre class="brush:php;toolbar:false">setTimeout(resolve, delay);

});
}

Using arrow functions and optional resolution value arguments, the code can be further condensed:

<br>const later = (delay, value) => new Promise(resolve => setTimeout(resolve, delay, value));<br>

Cancellable Promises (optional)

If you desire to cancel the timeout, you can return an object with a promise and a cancel method:

<br>const later = (delay, value) => {<br>  let timer = 0;<br>  let reject = null;<br>  const promise = new Promise((resolve, _reject) => {</p>
<pre class="brush:php;toolbar:false">reject = _reject;
timer = setTimeout(resolve, delay, value);

});
return {

get promise() { return promise; },
cancel() {
  if (timer) {
    clearTimeout(timer);
    timer = 0;
    reject();
    reject = null;
  }
}

};
};

This approach allows you to cancel the timeout and reject the promise using the cancel() method.

The above is the detailed content of How to Create and Manage Promises Using setTimeout in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn