settimeout-promise

setTimout in async/await style with es6 promises

Usage no npm install needed!

<script type="module">
  import settimeoutPromise from 'https://cdn.skypack.dev/settimeout-promise';
</script>

README

setTimeout promise

Greenkeeper badge NPM Version Build Status Known Vulnerabilities Test Coverage

Use setTimout es6 async/await style. setTimeout-promise is simple with zero dependecies.

Motivation

When using promises and async/await style and it's sometimes required to wait for X ms. It usually requires some boilerplate code to be written. setTimeout-promise saves you from writing this boilerplate code. So, instead of:

  //Do something
  const promise = new Promise((resolve)=>{
    setTimeout(resolve , 10)
  });
  await promise;
  //Do something after waiting;

You can use this module

  //Do something
  await waitFor(10);
  //Do something after waiting;

API

setTimeout-promise come with two simple functions:

  • waitFor(ms : number) : Promise<{}>
  • asyncTimeout(ms : number) : { promise : Promise<{}> , timer : NodeJS.Timeout}

So this means you can use if you just need to wait for X ms you can use waitFor:

   import {waitFor} from 'settimeout-promise'
   
   (async function(){
     await waitFor(10);
   })()

Or if you may need to cancel the timeout you can use asyncTimeout:

   import {asyncTimeout} from 'settimeout-promise'
   
   (async function(){
     const {promise , timer} = await asyncTimeout(10)
     promise.then(()=>{
       //This will never be invoked
     })
     //You need to cancel timeout
     clearTimeout(timer)
   })()

License

MIT