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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>    

chevron_right


Output:

  • Before Clicking the button:
  • After clicking the button:

Reference:Promise.prototype.then() Method

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.