Created
October 24, 2017 13:53
-
-
Save guillaumegarcia13/5c7f6e277d8d4a6d4d5d8b49fc386093 to your computer and use it in GitHub Desktop.
Promise.delay using Declaration Merging in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* On TypeScript Playground: https://goo.gl/EQVVUk */ | |
// Interface merging: https://www.typescriptlang.org/docs/handbook/declaration-merging.html | |
// declare global { | |
interface Promise<T> { | |
delay(duration?: number): Promise<T>; | |
} | |
// } | |
// Allow some sugar syntax | |
Promise.prototype.delay = function(duration: number) { | |
return this.then(function(value) { | |
return new Promise(function(resolve) { | |
setTimeout(function() { resolve(value); }, duration); | |
}) | |
}, function(reason) { | |
return new Promise(function(resolve, reject) { | |
setTimeout(function() { reject(reason); }, duration); | |
}) | |
}) | |
} | |
// Use this for throttling | |
const musicians = ['Clapton', 'U2', 'Muse', 'Coldplay']; | |
musicians.forEach((musician: string, index: number) => { | |
Promise.resolve(true).delay(2000 * index) | |
.then(() => { | |
const span = document.createElement('span'); | |
span.innerHTML = new Date() + ': <em>' + musician + '</em><br>'; | |
document.body.appendChild(span); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment