Problem
You want to create a function that creates a promise that delays for a given number of milliseconds.
Ingredients
- a function
- the
Promiseobject - the
setTimeout()function
Directions
-
Create a function that accepts the number of milliseconds.
function delay(ms) { ... }
-
Let the function return a promise object.
function delay(ms) { return new Promise(...); } -
Add the resolve-/reject-callback to the promise.
function delay(ms) { return new Promise( (resolve, reject) => { ... } ); } -
Inside that callback function call
setTimeout().function delay(ms) { return new Promise( (resolve, reject) => { setTimeout(resolve, ms); } ); } -
Voilá, a perfect delaying function in promise-style.
delay(5000).then(() => { console.log('Printed after 5 seconds.') });
Variants
-
If you want to pass data to the promise:
function delay(ms, data) { return new Promise( (resolve, reject) => { setTimeout(() => { resolve(data); }, ms); } ); }
Notes
- Promises are natively supported since ES2015. If you are using ES5 you may want to use one of the many polyfill libraries for Promises.