Last active
August 29, 2015 14:00
-
-
Save rhoot/e075b19acf8e6d6b2259 to your computer and use it in GitHub Desktop.
setImmediate polyfill using Promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Note: You probably do not want to use this in production code, as Promise is | |
// not supported by all browsers yet. | |
(function() { | |
"use strict"; | |
if (window.setImmediate) { | |
return; | |
} | |
var pending = {}, | |
nextHandle = 1; | |
function onResolve(handle) { | |
var callback = pending[handle]; | |
if (callback) { | |
delete pending[handle]; | |
callback.fn.apply(null, callback.args); | |
} | |
} | |
window.setImmediate = function(fn) { | |
var args = Array.prototype.slice.call(arguments, 1), | |
handle; | |
if (typeof fn !== "function") { | |
throw new TypeError("invalid function"); | |
} | |
handle = nextHandle++; | |
pending[handle] = { fn: fn, args: args }; | |
new Promise(function(resolve) { | |
resolve(handle); | |
}).then(onResolve); | |
return handle; | |
}; | |
window.clearImmediate = function(handle) { | |
delete pending[handle]; | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment