|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +// https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c |
| 4 | +// https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/#event-loop |
| 5 | +// https://html.spec.whatwg.org/multipage/webappapis.html#task-queue |
| 6 | + |
| 7 | +// The event loop as a process is a set of phases with specific tasks that are processed in a round-robin manner. |
| 8 | + |
| 9 | +const chalk = require('chalk'); |
| 10 | +const fs = require('fs'); |
| 11 | + |
| 12 | +const logger = { |
| 13 | + // timers |
| 14 | + t: function() { |
| 15 | + console.log(chalk.blue(' timers phase queue'), ...arguments); |
| 16 | + }, |
| 17 | + // poll phase (IO Callbacks) |
| 18 | + // it has a hard maximum (system dependent) before it stops polling for more events. |
| 19 | + p: function() { |
| 20 | + console.log(chalk.yellow(' poll phase queue'), ...arguments); |
| 21 | + }, |
| 22 | + // pending callbacks (some system operations) |
| 23 | + pc: function() { |
| 24 | + console.log(chalk.gray('pending callbacks'), ...arguments); |
| 25 | + }, |
| 26 | + /** |
| 27 | + * nextTick is not really the next tick, its just `immediate` and then |
| 28 | + * setImmediate is not really immediate at all, its more like the next tick |
| 29 | + * - Bert Belder |
| 30 | + */ |
| 31 | + // check |
| 32 | + // runs immediately after the poll phase completed or has become idle |
| 33 | + // fires on the following iteration or 'tick' of the event loop |
| 34 | + immediate: function() { |
| 35 | + console.log(chalk.magenta(' check phase'), ...arguments); |
| 36 | + }, |
| 37 | + // Tick - Will resolve before the event loop continues. |
| 38 | + // It allows you to "starve" your I/O by making recursive process.nextTick() calls |
| 39 | + // Alternative phrasing: |
| 40 | + // Allow the script to run to completion before executing the callback. |
| 41 | + tick: function() { |
| 42 | + console.log(chalk.cyan(' tick'), ...arguments); |
| 43 | + }, |
| 44 | + // close events |
| 45 | + ce: function() { |
| 46 | + console.log(chalk.gray('close events'), ...arguments); |
| 47 | + }, |
| 48 | +}; |
| 49 | + |
| 50 | +function shuffle(array) { |
| 51 | + for (let i = array.length - 1; i > 0; i--) { |
| 52 | + const j = Math.floor(Math.random() * (i + 1)); |
| 53 | + [array[i], array[j]] = [array[j], array[i]]; |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +function blockQueue(ms) { |
| 58 | + const startCallback = Date.now(); |
| 59 | + while (Date.now() - startCallback < ms) { |
| 60 | + // do nothing |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +const arr = [ |
| 65 | + |
| 66 | + () => { |
| 67 | + const m = 0; |
| 68 | + const scheduled = Date.now(); |
| 69 | + setTimeout(function() { |
| 70 | + const delay = Date.now() - scheduled; |
| 71 | + logger.t(`timeout ${m} (delay ${delay})`); |
| 72 | + }, m); |
| 73 | + console.log(`setTimeout(${m}) scheduled`); |
| 74 | + }, |
| 75 | + |
| 76 | + () => { |
| 77 | + const m = 1000; |
| 78 | + const scheduled = Date.now(); |
| 79 | + setTimeout(function() { |
| 80 | + const delay = Date.now() - scheduled - m; |
| 81 | + logger.t(`timeout ${m} (delay ${delay})`); |
| 82 | + }, m); |
| 83 | + console.log(`setTimeout(${m}) scheduled`); |
| 84 | + }, |
| 85 | + |
| 86 | + () => { |
| 87 | + const m = 0; |
| 88 | + const scheduled = Date.now(); |
| 89 | + const id = setInterval(function() { |
| 90 | + const delay = Date.now() - scheduled; |
| 91 | + logger.t(`interval ${m} (delay ${delay})`); |
| 92 | + clearInterval(id); |
| 93 | + }, m); |
| 94 | + console.log(`setInterval(${m}) scheduled`); |
| 95 | + }, |
| 96 | + |
| 97 | + () => { |
| 98 | + const total = 2; |
| 99 | + let count = 1; |
| 100 | + const m = 1000; |
| 101 | + const scheduled = Date.now(); |
| 102 | + const id = setInterval(function() { |
| 103 | + let delay = Date.now() - scheduled; |
| 104 | + delay -= m * count; |
| 105 | + logger.t(`interval ${m} ${count}/${total} (delay ${delay})`); |
| 106 | + count++; |
| 107 | + if (count > total) clearInterval(id); |
| 108 | + }, m); |
| 109 | + console.log(`setInterval(${m}) scheduled`); |
| 110 | + }, |
| 111 | + |
| 112 | + /*() => { |
| 113 | + const m = 1000; |
| 114 | + fs.readFile('index.js', function(err/*, data/) { |
| 115 | + if (err) throw err; |
| 116 | + blockQueue(m); |
| 117 | + logger.p(`read index.js (blocking ${m})`); |
| 118 | + }); |
| 119 | + console.log(`readFile (block ${m}) scheduled`); |
| 120 | + },*/ |
| 121 | + |
| 122 | + () => { |
| 123 | + const m = 2000; |
| 124 | + fs.readFile('index.js', function(err/*, data*/) { |
| 125 | + if (err) throw err; |
| 126 | + blockQueue(m); |
| 127 | + logger.p(`read index.js (blocking ${m})`); |
| 128 | + |
| 129 | + global.setImmediate(function() { |
| 130 | + logger.immediate('setImmediate'); |
| 131 | + }); |
| 132 | + }); |
| 133 | + console.log(`readFile (block ${m}) scheduled`); |
| 134 | + |
| 135 | + }, |
| 136 | + |
| 137 | + () => { |
| 138 | + // setImmediate() is actually a special timer that runs in a separate phase of the event loop. |
| 139 | + // It uses a libuv API that schedules callbacks to execute after the poll phase has completed. |
| 140 | + /** |
| 141 | + * The main advantage to using setImmediate() over setTimeout() is setImmediate() will always be executed |
| 142 | + * before any timers if scheduled within an I/O cycle, independently of how many timers are present. |
| 143 | + */ |
| 144 | + global.setImmediate(function() { |
| 145 | + logger.immediate('setImmediate'); |
| 146 | + }); |
| 147 | + console.log(`setImmediate scheduled`); |
| 148 | + }, |
| 149 | + |
| 150 | + () => { |
| 151 | + process.nextTick(function() { |
| 152 | + logger.tick('nextTick'); |
| 153 | + }); |
| 154 | + console.log(`nextTick scheduled`); |
| 155 | + }, |
| 156 | + |
| 157 | +]; |
| 158 | + |
| 159 | +function run() { |
| 160 | + shuffle(arr); |
| 161 | + |
| 162 | + console.log(chalk.white('start scheduling')); |
| 163 | + for (const fn of arr) { |
| 164 | + fn(); |
| 165 | + } |
| 166 | + console.log(chalk.white('done scheduling\n')); |
| 167 | +} |
| 168 | + |
| 169 | + |
| 170 | +global.setImmediate(function() { console.log('on main: immediate'); }); |
| 171 | +global.setTimeout(function() { console.log('on main: timeout'); }, 0); |
| 172 | +process.nextTick(function() { console.log('on main: next tick'); }); |
| 173 | + |
| 174 | +run(); |
| 175 | + |
| 176 | +console.log('on main: event loop for main complete'); |
0 commit comments