The event loop is one of the most important aspects of understanding nodes
- Introduction
- Stop the event loop
- Call stack
- A simple event loop description
- Queuing function execution
- message queue
- ES6 job queue
- in conclusion
Introduction
ThisEvent loopIt is one of the most important aspects about Node.
Why is this so important? Because it illustrates how Node implements asynchronous and non-blocking I/O, it basically illustrates Node's "killer application", which is what makes it successful.
The Node.js JavaScript code runs on a single thread. Only one thing happens at a time.
This limitation is actually very useful because it greatly simplifies your programming style without worrying about concurrency issues.
You only need to pay attention to how to write the code and avoid anything that may block the thread, such as synchronous network calls or infinitecycle.
Generally, in most browsers, each browser tab has an event loop to isolate each process and avoid web pages with infinite loops or heavy processing to block your entire browser.
The environment manages multiple concurrent event loops to handle, for example, API calls.Network workerIt can also run in its own event loop.
The main thing you need to worry about isYour codeWill run on a single event loop, and keep this in mind when writing code to avoid blocking it.
Stop the event loop
Any JavaScript code that takes a long time to return control to the event loop will block the execution of any JavaScript code in the page, or even block the UI thread, and the user cannot click to browse, scroll the page, etc.
Almost all I/O primitives in JavaScript are non-blocking. Network requests, file system operations, etc. Blocked is an exception, which is why JavaScript is so much based on callbacks, only recently based onpromisewithAsync/await.
Call stack
The call stack is a LIFO queue (last in, first out).
The event loop is constantly checkedCall stackSee if there are any functions that need to be run.
In doing so, it adds all the function calls it finds to the call stack and executes each function in sequence.
Do you know the error stack trace that you might be familiar with in the debugger or browser console? The browser looks up the function name in the call stack to inform you which function initiated the current call:
A simple event loop description
Let's take an example:
I use
foo
,bar
withbaz
AsRandom name. Enter any names to replace them.
const bar = () => console.log('bar')
const baz = () => console.log(‘baz’)
const foo = () => {
console.log(‘foo’)
bar()
baz()
}
foo()
This code prints
foo
bar
baz
As expected.
When this code runs, firstfoo()
Called. insidefoo()
Let's call firstbar()
And then we callbaz()
.
At this point, the call stack looks like this:
The event loop in each iteration checks whether there is something in the call stack and executes it:
Until the call stack is empty.
Queuing function execution
The above example looks normal, nothing special: JavaScript finds things to execute and runs them in order.
Let's see how to defer the function until the stack is cleared.
ExamplesetTimeout(() => {}), 0)
Just call a function, but once every other function in the code is executed, execute it.
for example:
const bar = () => console.log('bar')
const baz = () => console.log(‘baz’)
const foo = () => {
console.log(‘foo’)
setTimeout(bar, 0)
baz()
}
foo()
This code prints out, perhaps surprisingly:
foo
baz
bar
When this code is run, foo() will be called first. Inside foo(), we first call setTimeout,bar
As a parameter, we instruct it to run as fast as possible and pass 0 as the timer. Then we call baz().
At this point, the call stack looks like this:
This is the order of execution of all functions in the program:
Why is this so?
message queue
When calling setTimeout(), Browser or Node.js will startTimer. After the timer expires, in this case, we immediately set the timeout value to 0, and then put the callback function intomessage queue.
The message queue is also a user-initiated event, such as a click or keyboard event, orBring itQueuing the responses before your code has a chance to respond to them. Or alsoDOMEvents like thisonLoad
.
The loop assigns priority to the call stack. It first processes everything found in the call stack, and once there is nothing in it, it starts processing the content in the message queue.
We don't have to wait for things likesetTimeout
, Crawling or other ways to do your own work, because they are provided by the browser, and they are in their own thread. For example, if you setsetTimeout
The timeout is 2 seconds, you don't have to wait 2 seconds-the wait happens elsewhere.
ES6 job queue
ECMAScript 2015The concept of job queue is introduced, and Promises uses this queue (also introduced in ES6/ES2015). This is a way to execute the result of an asynchronous function as quickly as possible, rather than at the end of the call stack.
Promises resolved before the end of the current function will be executed immediately after the current function.
I find the roller coaster analogy in an amusement park is good: the message queue puts you behind the queue, behind everyone else, you will have to wait for the turn, and the work queue is a fast-track ticket so you can finish Ride another ride immediately after one ride.
example:
const bar = () => console.log('bar')
const baz = () => console.log(‘baz’)
const foo = () => {
console.log(‘foo’)
setTimeout(bar, 0)
new Promise((resolve, reject) =>
resolve(‘should be right after baz, before bar’)
).then(resolve => console.log(resolve))
baz()
}
foo()
This print
foo
baz
should be right after baz, before bar
bar
This is Promises (and Async/await built on Promise) and throughsetTimeout()
Or other platform APIs.
in conclusion
This article introduces you to the basic building blocks of the Node.js event loop.
This is an important part of any program written in Node.js, and I hope that some of the concepts presented here will be useful to you in the future.
Download mine for freeNode.js manual
More node tutorials:
- Introduction to npm package manager
- Introduction to Node.js
- HTTP request using Axios
- Where to host Node.js applications
- Use Node.js to interact with Google Analytics API
- npx node package runner
- package.json guide
- Where does npm install packages?
- How to update Node.js
- How to use or execute packages installed with npm
- package-lock.json file
- Semantic version control using npm
- Should you submit the node_modules folder to Git?
- Update all Node dependencies to the latest version
- Use Node.js to parse JSON
- Find the installed version of the npm package
- Node.js flow
- Install an older version of the npm package
- Get the current folder in Node
- How to record objects in Node
- Use export to expose functions from Node files
- Difference between node and browser
- Use Node to make HTTP POST requests
- Use Node to get HTTP request body data
- Node buffer
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use Node.js REPL
- Node, accepts parameters from the command line
- Use Node to output to the command line
- Accept input from the command line in Node
- Use `npm uninstall` to uninstall the npm package.
- npm global or local package
- npm dependencies and devDependencies
- Node.js event loop
- Understanding process.nextTick()
- Understanding setImmediate()
- Node event emitter
- Set up an HTTP server
- Use Node to make HTTP requests
- Node fs module
- HTTP request in Node using Axios
- Use Node to read files
- Node file path
- Write file with Node
- Node file statistics
- Use file descriptors in Node
- Use folders in Node
- Node path module
- Node http module
- Combine WebSockets with Node.js
- Basic knowledge of using MySQL and Node
- Error handling in Node.js
- Pug Guide
- How to read environment variables from Node.js
- How to exit from Node.js program
- Node os module
- Node event module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to delete files using Node.js
- How to get the last update date of a file using Node.js
- How to determine whether the date is today in JavaScript
- How to write a JSON object to a file in Node.js
- Why use Node.js in the next project?
- Run web server from any folder
- How to use MongoDB with Node.js
- Use Chrome DevTools to debug Node.js applications
- What is pnpm?
- Node.js runtime v8 options list
- How to solve the "missing write access permission" error when using npm
- How to enable ES modules in Node.js
- How to use Node.js to generate child processes
- How to get the parsed body and the original body at the same time in Express
- How to handle file upload in Node.js
- What is the peer dependency in the node module?
- How to write a CSV file using Node.js
- How to use Node.js to read CSV files
- Node core module
- Use Node.js to increase the number of multiple folders at once
- How to print canvas to data URL
- How to create and save images using Node.js and Canvas
- How to download images using Node.js
- How to batch rename files in Node.js
- How to get the names of all files in a folder in Node
- How to use promise and wait function based on Node.js callback
- How to test NPM packages locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Use Node.js to serve HTML pages
- How to solve the error that util.pump in Node.js is not a function