Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money
Hello everyone, I am quick-frozen fish 🐟, a front end of water system 💦, like colorful whistle 💐, continuous sand sculpture 🌲, I am a good brother of the next door Cold grass Whale, I just started to write an article. If you like my article, you can follow ➕ to like it, inject energy into me, and grow with me
Warm tips ☀️: there are a lot of articlesGIF images
, it may be slow to load, please be patient (I tried to compress the purr)
Read this article 🦀
1. What will you learn about the event loop
2. Why can javascript execute asynchronous functions when it is single-threaded
3. Why do browsers use event loops
4. What will you learn about javaScript runtime
5. You’ll learn about the connection between event loops and browser redraw
Preface 🌵
JavaScript programmers like to use words like “event loop,” “non-blocking,” “callback,” “asynchronous,” “single thread,” and “concurrent.” It all seems obvious, but finding a good explanation of how JavaScript actually works isn’t that easy, so let’s learn! 🕶
Pre-knowledge 👋
What is a javaScript
JavaScript is an interpreted language, not a compiled language. Programs like C++ or Java need to be compiled before they can be run. The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute. In contrast, JavaScript has no compilation steps. Instead, the interpreter in the browser reads the JavaScript code, interprets each line, and then runs it. More modern browsers use a technique called just-in-time (JIT) compilation, which compiles JavaScript into executable bytecode that is ready to run.
- Single-threaded (equivalent to one worker in a workshop)
- Single concurrent (can only do one thing at a time)
- There is a call stack (javaScript execution context)
- An event loop (retrieves callback functions from the callback queue and puts them on the call stack so they can be executed.)
- A callback queue (which is a data structure containing all callback functions ready to execute.)
- Some other apis
What is the javaScirpt runtime
JavaScript runs in V8, Google’s open source high-performance javaScript and WebAssembly engine, written in C++.
- Heap mainly holds our objects
- Stack is the execution context for our javaScript, as well as some basic data types
What is the WebAPI
Extra things that browsers provide, like DOM, AJAX, TIMEOUT, and so on
The Web API is a function provided to the engine, but is not part of the JavaScript language itself.
What is an event loop
An event loop is a programming construct or design pattern for waiting for and dispatching events or messages in a program. Event loops work by making a request to some internal or external “event provider” (usually blocking the request before the event arrives) and then calling the relevant event handler (” scheduling the event “). Event loops are sometimes called message dispatchers, message loops, message pumps, or run loops.
The text 🦁
Put all of these things together and you’ll find an EventLoop
JavaScript execution mechanism
Take a look at the picture and get a general impression of what I’m going to say. I’ll explain it one by one later.
JavaScript is a single-threaded programming language that, when run single-threaded, has a single call stack.
It can only do one thing at a time, that’s what single-threaded means, a program can run one piece of code at a time. Let’s just look at the picture.
So the call stack is basically it’s a data structure that basically keeps track of where we are in the program, and if we go into a function, we put that function on the stack, and if we return from a function, we pop it off the top of the stack.
That’s when our program goes wrong, why do you see something like this on the console
I believe you have encountered a stack of memory overflow, this nested loop, will continue to open up memory space in our stack eventually overflow, resulting in an error
When our synchronization code is slow to execute
Let’s simulate that our network requests are synchronous
If all of our code is executed synchronously, then it blocks our thread, and when our thread is blocked there’s nothing we can do but wait, obviously making network requests that are synchronous, that can have serious consequences. But javaScript is single-threaded, so what’s the solution?
Of course you are executing these time-consuming operations asynchronously (AJAX, TimeOut, etc.), so you might say, well, javaScript is single-threaded, but how can you execute asynchronous functions?
Browsers have long thought of this. AJAX, TimeOut, etc., the WebAPIs that browsing provides to javaScript engines, are not part of the javaScript language.
When we execute an asynchronous function we hand it over to the browser to manage, which is what we have here
WebAPIs
:
The browser provides us with apis for executing asynchronous functions, which are managed by the browser and separated from our javaScript execution call stack.
Callbak Queue
:
When our asynchronous function is ready to execute, the browser pushes its Callback to our Callback Queue
EventLoop
:
When there are no statements in our javaScript execution Stack to execute, the EventLoop pulls the queue header callback from our queue, pushes it to our Stack, waits for the Stack to complete, and continues fetching the queue header callback, and so on.
Sample 🐳
Example 1 Setting a timer ⌚️
- First the console prints Hi
- Go to the second sentence
setTimeout
It was handed to us at this timeThe browser
The browser will start a timer for you that’s not in the javaScript runtime. - Execute the third sentence to print JSConfEu
- when
Five seconds,
After that, the browser will put ourSetTimeout callback function
Up to theCallBack Queue
(Task Queue) In the queue whenstack
When there are no statements in the stack to execute,evnet Loop
It’s going to be fetched from our CallBack QueueThe callback function
toExecution stack
To execute. - Finally, print “There”
Hi=>JSConfEui=>there
Even if you set SetTimeout to 0, it will follow the steps above
Example 2 sends an asynchronous network request 🍪
- First print Hi
- An asynchronous network request is then sent to the browser for processing.
- Execute the third sentence to print JSConfEU
- When the request completes, the browser pushes it to the Task Queue (also known as callback Queue)
- When the stack has no statements to execute, EventLoop pulls the callback function for the network request from the Task Queue and pushes it onto the stack for execution
- Finally, the result of the network request is printed
Association of event loops and browser redraws 🌽
- It’s important to know that if we have code on the stack that hasn’t finished executing, our browser won’t be able to render until the stack is cleared
- Rendering takes precedence over callback functions
The following GIF is not very clear, I posted the code here
When the function in the stack is finished, we do a redraw, and then go to the callback queue to fetch the callback function and execute it on the stack, and so on
Reference 📚
-
wiki
-
MDN
-
JSConf
Harvest 🍁
What do we learn in the passageEvent loop
, as well asHow JavaScript works
And what isV8
And what isWebAPI
Learning the underlying principles can broaden my horizon, understand the nature of javaScript from the root, and quickly locate problems. I also hope you can gain something from this article. I hope this article will be helpful to you
Conclusion 🌞
So I N article is over, actually very simple, the purpose of the article is the summary of daily work and output, output some feel useful things for people, food is not food is not important, but love 🔥, hope everyone can like my articles, I am really very attentively in writing, also hope that through articles meet more like-minded friends, if you like, Welcome to add my friends, sand sculpture, progress together.
Making 🤖 : sudongyu
Personal blog 👨💻: Frozen fish blog
Vx 👦 : sudongyuer
Write in the last
Guys, if you like my words, give 🐟🐟 a thumbs up 👍 or follow ➕ to support me the most.
Add me on wechat: Sudongyuer, invite you into the group and learning the front together, become a better engineer ~ (group of qr code here – > front to go to bed early, qr code has expired, see the links to the boiling point in the comments, I will put the latest qr code in the comments section, of course, can also add me WeChat I pull you into the group, after all, I also interesting front-end, know I am not bad 🌟 ~)