{"id":14002,"library":"setimmediate","title":"setImmediate Polyfill and Shim","description":"The `setImmediate.js` package provides a robust, cross-browser polyfill and shim for the `setImmediate` and `clearImmediate` APIs, originally proposed by Microsoft to the Web Performance Working Group. On its current stable version 1.0.5 (last updated in 2016), it bridges the gap for efficient, non-blocking asynchronous execution, especially in older or less-spec-compliant environments. Unlike `setTimeout(..., 0)` or `process.nextTick` (in newer Node.js), `setImmediate` queues a task on the *macrotask* queue, yielding control back to the event loop before execution, allowing for rendering or I/O to occur. It differentiates itself by employing various \"clever tricks\" such as `postMessage`, `MessageChannel`, and historical browser-specific hacks (`<script> onreadystatechange`, `process.nextTick` in older Node) to achieve optimal performance and correct macrotask semantics across IE6+, Firefox 3+, WebKit, Opera 9.5+, and Node.js. In environments where these tricks aren't viable, it gracefully falls back to `setTimeout`, ensuring universal compatibility.","status":"maintenance","version":"1.0.5","language":"javascript","source_language":"en","source_url":"https://github.com/yuzujs/setImmediate","tags":["javascript"],"install":[{"cmd":"npm install setimmediate","lang":"bash","label":"npm"},{"cmd":"yarn add setimmediate","lang":"bash","label":"yarn"},{"cmd":"pnpm add setimmediate","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package primarily operates by patching the global scope, making `setImmediate` available globally without explicit named imports in the consumer's module. The `require('setimmediate')` statement in Node.js is for its side effect of polyfilling the global object.","wrong":"import { setImmediate } from 'setimmediate';","symbol":"setImmediate","correct":"// In Node.js: require('setimmediate');\n// In browser: Include <script src=\"setimmediate.js\"></script>\n// (setImmediate becomes a global function)"},{"note":"Similar to `setImmediate`, `clearImmediate` is exposed globally as a side effect of loading the package, without requiring a specific module import for the function itself.","wrong":"import { clearImmediate } from 'setimmediate';","symbol":"clearImmediate","correct":"// No explicit import needed; `clearImmediate` is made global."},{"note":"This CommonJS `require` statement is the intended way to load the polyfill in Node.js environments. Its primary purpose is to execute the module's code, which then patches the global scope with `setImmediate` and `clearImmediate`.","wrong":"import * as setimmediate from 'setimmediate';","symbol":"(Module side effect)","correct":"require('setimmediate');"}],"quickstart":{"code":"require('setimmediate');\n\nconsole.log('Start script');\n\nlet count = 0;\nfunction processNextItem() {\n  if (count < 3) {\n    console.log(`Processing item ${count}`);\n    count++;\n    // Use setImmediate to yield to the event loop, then continue processing.\n    // This allows I/O, rendering, or other macrotasks to run between calls.\n    setImmediate(processNextItem);\n  } else {\n    console.log('Finished processing items.');\n  }\n}\n\nsetImmediate(processNextItem); // Kick off the first task\n\nconsole.log('Script end (synchronous part)');\n\n// Demonstrating macrotask vs. microtask execution order:\nPromise.resolve().then(() => console.log('Promise microtask executed'));\nprocess.nextTick(() => console.log('process.nextTick microtask executed'));\n// setImmediate will run *after* all microtasks are exhausted and before the next rendering/I/O turn.","lang":"javascript","description":"Demonstrates how to use the globally available `setImmediate` for non-blocking asynchronous execution, highlighting its macrotask semantics compared to microtasks like Promises or `process.nextTick`."},"warnings":[{"fix":"Always be explicit about whether macrotask (e.g., `setImmediate`, `setTimeout`, I/O events) or microtask (e.g., Promises, `process.nextTick`) semantics are required for your asynchronous operations. If you need immediate execution within the same event loop tick, use a microtask-based solution.","message":"The `setImmediate` API operates on the macrotask queue, which is fundamentally different from the microtask queue used by `Promise.then()`, `queueMicrotask()`, and `process.nextTick()` (in Node.js v0.9+). Misunderstanding this distinction can lead to unexpected execution order and race conditions when mixing macrotask and microtask scheduling.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade to `setimmediate@1.0.4` or newer to ensure robust and correctly asynchronous behavior across all supported browser environments.","message":"Version 1.0.4 reverted the `<img> onerror` trick used in 1.0.3 and earlier versions for browser-based scheduling, because it was found not to be reliably asynchronous. This change impacts environments where that specific trick was used, ensuring more correct async behavior.","severity":"breaking","affected_versions":"=1.0.3"},{"fix":"Update to `setimmediate@1.0.3` or newer. If upgrading is not an option, avoid using string arguments with `setImmediate` (e.g., `setImmediate(\"myFunction()\")`); instead, pass a direct function reference (e.g., `setImmediate(myFunction)`).","message":"Older versions of `setimmediate.js` (pre-1.0.3) used `eval` to obtain the global object when `setImmediate` was invoked with string arguments, which could lead to Content Security Policy (CSP) violations in strict environments.","severity":"gotcha","affected_versions":"<1.0.3"}],"env_vars":null,"search_vec":"'0':65 '1.0.5':38 '2016':42 'allow':88 'api':22 'asynchron':52 'back':81 'block':51 'bridg':44 'browser':13,110 'browser-specif':109 'clearimmedi':21 'clever':101 'compliant':61 'control':80 'cross':12 'cross-brows':11 'current':35 'differenti':96 'effici':48 'employ':99 'environ':62 'especi':54 'event':84 'execut':53,87 'gap':46 'group':32 'hack':112 'histor':108 'i/o':92 'last':39 'less':59 'less-spec-compli':58 'loop':85 'macrotask':77 'messagechannel':106 'microsoft':26 'newer':69 'node.js':70 'non':50 'non-block':49 'occur':94 'older':56 'origin':23 'packag':7 'perform':30 'polyfil':2,14 'postmessag':105 'process.nexttick':67 'propos':24 'provid':8 'queue':72,78 'render':90 'robust':10 'setimmedi':1,19,71 'setimmediate.js':6 'settimeout':64 'shim':4,16 'spec':60 'specif':111 'stabl':36 'task':74 'trick':102 'unlik':63 'updat':40 'various':100 'version':37 'web':29 'work':31 'yield':79","created_at":"2026-04-20T01:57:25.737649+00:00","updated_at":"2026-04-20T01:57:25.737649+00:00","problems":[{"fix":"In Node.js, ensure `require('setimmediate');` is called at the application's entry point. In browser environments, verify that the `<script>` tag loading `setimmediate.js` is correctly placed and loaded before any calls to `setImmediate`.","cause":"The `setImmediate` polyfill was not loaded or executed in the current environment before `setImmediate` was called.","error":"ReferenceError: setImmediate is not defined"},{"fix":"Upgrade the `setimmediate` package to version 1.0.3 or newer. If an upgrade is not feasible, ensure that `setImmediate` is always called with a function reference, never with a string that would require `eval`.","cause":"Using an older version of `setimmediate.js` (prior to 1.0.3) and passing string arguments to `setImmediate` in a browser environment with a strict Content Security Policy.","error":"Content Security Policy: The page’s settings blocked the loading of a resource at inline (‘script-src’...)"},{"fix":"Rethink the asynchronous flow. If an operation needs to run immediately after a Promise resolves, it should be chained with another `.then()`. If it explicitly needs to yield to the event loop for I/O or rendering before executing, `setImmediate` is correct, but be aware of its position in the task queue relative to microtasks.","cause":"Misunderstanding the execution order difference between microtasks (like `Promise.then()` and `process.nextTick()`) and macrotasks (`setImmediate`, `setTimeout`). `setImmediate` will always run after all microtasks have been exhausted within a given event loop turn.","error":"Error: Calling `setImmediate` inside a Promise.then() handler results in unexpected ordering."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/yuzujs/setImmediate","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/setimmediate","openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}