Skip to content

Instantly share code, notes, and snippets.

@englishextra
Last active May 17, 2016 19:45
Show Gist options
  • Save englishextra/f4a5b2f47573af15d1ed206ac240c8d7 to your computer and use it in GitHub Desktop.
Save englishextra/f4a5b2f47573af15d1ed206ac240c8d7 to your computer and use it in GitHub Desktop.
setImmediate polyfill for the browser and node
/*!
* setImmediate polyfill for the browser and node
* modified github.com/taylorhakes/setAsap
* added: !window.setImmediate&&(window.setImmediate=window.setAsap);
* gist.github.com/englishextra/f4a5b2f47573af15d1ed206ac240c8d7
* This is an alternative to setTimeout(fn, 0), which behaves like setTimeout(fn, 4).
* setAsap will execute immediately. It has unmatched performance and is extremely lightweight.
* nczonline.net/blog/2011/09/19/script-yielding-with-setimmediate/
* setAsap(function() {
* // do something async
* });
*/
!function(e,t){"use strict";function n(){return 9007199254740991===s?0:++s}var o="object"==typeof window&&window||"object"==typeof global&&global||"object"==typeof self&&self||e,r="function"==typeof setImmediate,i="object"==typeof process&&!!process&&"function"==typeof process.nextTick,s=0,a=function(){var e,t,s,a;if(o.MutationObserver)return function(t){e=document.createElement("div"),new MutationObserver(function(){t(),e=null}).observe(e,{attributes:!0}),e.setAttribute("i","1")};if(!r&&o.postMessage&&!o.importScripts&&o.addEventListener){var c="com.setImmediate"+Math.random();a={};var u=function(e){if(e.source===o&&0===e.data.indexOf(c)){var t=e.data.split(":")[1];a[t](),delete a[t]}};return o.addEventListener("message",u,!1),function(e){var t=n();a[t]=e,o.postMessage(c+":"+t,"*")}}return!r&&o.document&&"onreadystatechange"in document.createElement("script")?function(e){t=document.createElement("script"),t.onreadystatechange=function(){t.onreadystatechange=null,t.parentNode.removeChild(t),t=null,e()},document.body.appendChild(t)}:(s=r&&setImmediate||i&&process.nextTick||setTimeout,function(e){s(e)})}();"undefined"!=typeof module&&module.exports?module.exports=a:"undefined"!=typeof require&&require.amd?define(function(){return a}):o.setAsap=a}(this);!window.setImmediate&&(window.setImmediate=window.setAsap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment