Posts Tagged ‘ECMAscript2015’

Promises, Promises… Timeout!

25 Apr

I was playing with ES6’s new Promises, for the first time, this week. Then, I was looking at the ugliness of using a browser’s setTimeout() function and thought that it would look better as a Promise.

tl;dr summary: A Simple Promise Version of “setTimeout()”

If we do it right, you simply specify the timeout period and implement a handler for then() to invoke:

timeout(5000) // Delay for 5000 ms
   .then(function () {
      // Do, here, whatever should happen when the time has elapsed…

Or, since this is ES6, we might as well use arrow-function shorthand:

timeout(5000).then( () => {
   // do your thing, here…


The setTimeout() already functions a bit like a Promise, without matching the promise-pattern and syntax, so converting it to a Promise is pretty easy:

function timeout(delay) {
   return new Promise( 
      (resolve, reject) => setTimeout( resolve, delay )
} // timeout()

This all, in contrast to the “old” way of using setTimeout():

setTimeout(function () {
   // This is where I do my thing, when the timer pops…
}, 5000);

It just looks ugly; the invocation of the timer and its delay-time property is mingled with what happens when the timer triggers. With the promise pattern, the semantics of the invocation and the handling are discretely organized between the timeout() and its then() handler. Read the rest of this entry »