{"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.","language":"javascript","status":"maintenance","last_verified":"Sun Apr 19","install":{"commands":["npm install setimmediate"],"cli":null},"imports":["// In Node.js: require('setimmediate');\n// In browser: Include <script src=\"setimmediate.js\"></script>\n// (setImmediate becomes a global function)","// No explicit import needed; `clearImmediate` is made global.","require('setimmediate');"],"auth":{"required":false,"env_vars":[]},"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`.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}