Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active December 16, 2015 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/5404449 to your computer and use it in GitHub Desktop.
Save barneycarroll/5404449 to your computer and use it in GitHub Desktop.
Still beating around the bush of Promises, a simple wrapper for `setTimeout(fn, 0)` (a technique used in DOM scripting to defer execution to the end of the stack) that returns `status` and `cancel` methods. When I thought a bit more about [later.js](https://gist.github.com/barneycarroll/5403872) I realised a bit of extension was almost natural. …
function Later( fn ){
// 0: pending; 1: resolved; 2: cancelled;
var status = 0;
var resolve = setTimeout( function resolve(){
fn();
status = 1;
}, 0);
return {
cancel : function cancel(){
// Can't cancel an event that's already executed
if( !status ){
clearTimeout(deferral);
status = 2;
}
},
status : function getStatus(){
return [ 'pending', 'resolved', 'cancelled' ][ status ];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment