Home >Web Front-end >JS Tutorial >How to Create and Manage Promises Using setTimeout in JavaScript?
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.
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");
});
});
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>
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!