JS promise : Wrap settimeout in promise


/ Published in: JavaScript
Save to your folder(s)

Warp settimeout function in promise


Copy this code and paste it in your HTML
  1. var milllisecond = 4000;
  2. function wait(ms){
  3. console.log('started');
  4. // new promise
  5. return new Promise(function(resolve,reject){
  6. console.log(this);
  7. window.setTimeout(function(){
  8. // resolve inside the callback of settimeout
  9. resolve(ms);
  10. reject(ms);
  11. },ms);
  12. });
  13. };
  14.  
  15. wait(milllisecond).then(finish);
  16.  
  17. function finish(a){
  18. console.log(1+a)
  19. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.