Skip to content

Instantly share code, notes, and snippets.

@rhoot
Last active August 29, 2015 14:00
Show Gist options
  • Save rhoot/e075b19acf8e6d6b2259 to your computer and use it in GitHub Desktop.
Save rhoot/e075b19acf8e6d6b2259 to your computer and use it in GitHub Desktop.
setImmediate polyfill using Promise
// 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