How to wrap setTimeout() method in a promise ?
To wrap setTimeout in a promise returned by a future. We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes upto two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise. There can be two different values if the function called onFulfilled that’s mean promise is fulfilled. If the function onRejected called that means promise is rejected.
Syntax:
Promise.then(onFulfilled, onRejected)
Below example will illustrate the approach:
Example:
<!DOCTYPE html><html> <head> <title> How to wrap setTimeout in a promise? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to wrap setTimeout in a promise? </h3> <br> <button onclick="change()"> Click to print </button></body> <script> function change() { return new Promise(function(resolve, reject) { // Setting 2000 ms time setTimeout(resolve, 2000); }).then(function() { console.log("Wrapped setTimeout after 2000ms"); }); }</script> </html> |
Output:
- Before Clicking the button:

- After clicking the button:

Reference:Promise.prototype.then() Method


