Is there a version of setTimeout that returns an ES6 promise?

In Browsers

First of all no – there is no built in for this. Lots of libraries that enhance ES2015 promises like bluebird whip with it.

I think the other answer conflates executing the function and a delay, it also creates timeouts that are impossible to cancel. I’d write it simply as:

function delay(ms){
    var ctr, rej, p = new Promise(function (resolve, reject) {
        ctr = setTimeout(resolve, ms);
        rej = reject;
    });
    p.cancel = function(){ clearTimeout(ctr); rej(Error("Cancelled"))};
    return p; 
}

Then you can do:

delay(1000).then(/* ... do whatever */);

Or

 doSomething().then(function(){ return delay(1000); }).then(doSomethingElse);

If we only want the basic functionality in ES2015, it’s even simpler as:

let delay = ms => new Promise(r => setTimeout(r, ms));

In Node

You can use util.promisify on setTimeout to get a delay function back – meaning you don’t have to use the new Promise constructor anymore.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)