Skip to content

Instantly share code, notes, and snippets.

@micjamking
Last active July 14, 2020 03:16
Show Gist options
  • Save micjamking/64b643a977a3b46365ae00ac8d374034 to your computer and use it in GitHub Desktop.
Save micjamking/64b643a977a3b46365ae00ac8d374034 to your computer and use it in GitHub Desktop.
Chaining delays in JavaScript (setTimeout) using Promises (ie. delay(func1, 1000).delay(func2, 1000).delay(func3, 1000))
/**
* Daisy chaining delays (setTimeout) using Promises
*
* Ex: delay(func1, 1000).delay(func2, 1000).delay(func3, 1000);
*
* @param {Function} cb - Callback function
* @param {Number} ms - Time delay (in milliseconds)
* @return chainable delay Promise (ie. delay(cb, ms).delay(cb, ms).delay(cb, ms)...)
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Creating_a_Promise_around_an_old_callback_API
* @see http://2ality.com/2013/03/subclassing-builtins-es6.html
* @see https://stackoverflow.com/a/6921279/933951
* @see https://gist.github.com/domenic/8ed6048b187ee8f2ec75#file-angularpromise-js-L20
*/
function delay (cb, ms) {
// MyPromise constructor - subclass of Promise
function MyPromise(fn) {
var promise = new Promise((resolve, reject) => fn(resolve, reject));
promise.__proto__ = MyPromise.prototype;
return promise;
}
// MyPromise should extend Promise
MyPromise.__proto__ = Promise;
MyPromise.prototype.__proto__ = Promise.prototype;
// Extend MyPromise to return delay from promise success
MyPromise.prototype.delay = function (cb, ms) {
return this.then( () => delay(cb, ms) );
}
// Create internal 'wait' promise using setTimeout
let _wait = ms => new MyPromise( resolve => setTimeout(resolve, ms) );
return _wait(ms).then(cb);
}
@Debdut
Copy link

Debdut commented Jul 14, 2020

Hi, thanks for this. But my problem is deeper.

Suppose delay is a method in a class, then how will you do it?
I was trying to implement delay in this library url-request.

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