Skip to content

Instantly share code, notes, and snippets.

@muhsin-k
Last active March 18, 2018 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muhsin-k/27a0b288707caeaa3bf2e32d8da30f3c to your computer and use it in GitHub Desktop.
Save muhsin-k/27a0b288707caeaa3bf2e32d8da30f3c to your computer and use it in GitHub Desktop.
Nodejs event loop [One Tick Of Event Loop in NodeJS]
// Suppose we are running ,node myFile.js
const pendingTimers = [];
const pendingOSTasks = [];
const pendingOperations = [];
// New timers, tasks, operations are recorded from myFile running [We are pretending here]
myFile.runContents();
function shouldContinue() {
// Check one: Any pending setTimeout, setInterval, setImmediate?
// Check two: Any pending OS tasks? (Like server listening to port)
// Check three: Any pending long running operations? (Like fs module)
return (
pendingTimers.length || pendingOSTasks.length || pendingOperations.length
);
}
// Entire body executes in one 'tick'
while (shouldContinue()) {
// 1) Node looks at pendingTimers and sees if any functions
// are ready to be called. setTimeout, setInterval
// 2) Node looks at pendingOSTasks and pendingOperations
// and calls relevant callbacks
// 3) Pause execution. Continue when...
// - a new pendingOSTask is done
// - a new pendingOperation is done
// - a timer is about to complete
// 4) Look at pendingTimers. Call any setImmediate
// 5) Handle any 'close' events
}
// exit back to terminal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment