Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active July 29, 2022 20:02
Show Gist options
  • Save joepie91/2664c85a744e6bd0629c to your computer and use it in GitHub Desktop.
Save joepie91/2664c85a744e6bd0629c to your computer and use it in GitHub Desktop.
ES6 Promise.delay
module.exports = function(duration) {
return function(){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve();
}, duration)
});
};
};
// Usage:
var delayPromise = require("./delay-promise");
doThing()
.then(...)
.then(delayPromise(5000))
.then(...)
@nbouvrette
Copy link

@justml @jgerstle

I confirm that the following code works perfectly with Node.js:

const wait = require('util').promisify(setTimeout);

(async () => {
    console.log('Wait...');
    await wait(1000);
    console.log('...a second.');
})();

@berstend
Copy link

berstend commented Nov 13, 2019

Hello future self, here's the TypeScript version for your copy/pasting pleasure:

const delay = (ms: number) => new Promise(_ => setTimeout(_, ms))

and my favorite JS version:

const delay = ms => new Promise(_ => setTimeout(_, ms))

@tolotrasmile
Copy link

You forget to clear the setTimeout

const delay = async <T>(timeout: number, value?: T) => {
    return new Promise((resolve) => {
        const timeoutId = setTimeout(() => {
            resolve(value);
            clearTimeout(timeoutId);
        }, timeout);
    });
};

@joepie91
Copy link
Author

joepie91 commented May 5, 2020

@tolotrasmile That shouldn't be necessary, since this is a setTimeout, not a setInterval. A setTimeout only ever fires once, so once you're in the callback, there is nothing to clearTimeout anymore.

clearTimeout is basically just for cancelling a setTimeout that has not yet occurred.

@sannajammeh
Copy link

For nodeJS only

import { setTimeout } from "timers/promises";

await setTimeout(3000, value);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment