Skip to main content

Command Palette

Search for a command to run...

Using setTimeout on promise chain

Updated
•1 min read•View as Markdown
Using setTimeout on promise chain

The built-in function setTimeout uses callbacks. How can we create a promise-based alternative that can then be chained. We will need to use promise that would be resolved after ms milliseconds, so that we can add .then to it, like this:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)
   });
}

Promise.prototype.delay = function(t) {
    return this.then(function(v) {
        return delay(t, v);
    });
}

Promise.resolve("hello").delay(500).then(function(v) {
    console.log(v);
});

The shorter ES6 version of the answer:

const delay = t => new Promise(resolve => setTimeout(resolve, t));

delay(3000).then(() => console.log('Hello'));

Please note that in this task resolve is called without arguments. We don’t return any value from delay, just ensure the delay.

More from this blog

I

Is A Web Learning

54 posts