Last active
September 10, 2024 11:47
-
-
Save isabellachen/e35855acf67490d68b85dc726992cf2f to your computer and use it in GitHub Desktop.
Node's Event Loop implementation in pseudo code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// node's event loop behind the scenes | |
// node is event driven and single threaded, with background workers | |
// imagine we ran node index.js | |
const pendingTimers = [] | |
const pendingOSTasks = [] | |
const pendingOperations = [] | |
// node executes the file and triggers timers, OSTasks and operations, filling in the above arrays. | |
index.runContents() | |
function shouldContinue () { | |
// check one: Any pending setTimeout, setInterval or setImmediate? | |
// check two: Any pending OS tasks? (Like server listening to port) | |
// check three: Any pending operations? (Like fs module) | |
} | |
// every iteration of the loop is one 'tick' | |
while (shouldContinue()) { | |
// 1: have any timers expired? If so, put their callbacks in the event loop and execute them. | |
// 2: are there any resolved OS tasks? Like, if a response is recieved in a port, put the callback in the event loop and execute the callback | |
// 3: the event loop is now empty, pause execution. | |
// 3b: continue execution when node is notified | |
// - timer has expired | |
// - pending OS task is done | |
// - operation completed | |
// look at pending timers and call any setImmediate | |
// handle any close/ cleanup events | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment