Last active
March 18, 2018 04:36
-
-
Save muhsin-k/27a0b288707caeaa3bf2e32d8da30f3c to your computer and use it in GitHub Desktop.
Nodejs event loop [One Tick Of Event Loop in NodeJS]
This file contains 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
// 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