This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021
preface
In the past few articles, we have documented several JavaScript Event functions, as well as other related topics:
In this article, we’ll learn about events and event loops in JavaScript in browsers
Events and event loops
JavaScript has a concurrency model based on event loops, which are responsible for executing code, collecting and processing events, and executing subtasks in queues.
In the context of an event loop, the browser event handler is written the same as any other asynchronous notification. They are scheduled when an event occurs, but must wait for other scripts running before they can run.
Event loop
Let’s say a function performs a square calculation of a number. If you want to perform a heavy, long-running calculation in a separate thread, you can respond by using a separate squareworker.js file with one of the calculation functions described earlier and sending back a message
postMessage(ev){ return ev }
addEventListener("message".event= > {
postMessage(event.value * event.value)
})
Copy the code
An event loop is called an event loop because it is implemented like this:
while (queue.waitForMessage()) {
queue.processNextMessage()
}
Copy the code
Queue.waitformessage () waits synchronously for messages to arrive (if there are no messages currently waiting to be processed).
“Execute to complete” After each message has been fully executed, other messages will not be executed. This provides some excellent features for program analysis, including: when a function executes, it is not preempted, and only after it has finished does any other code run to modify the data that the function operates on. If a function runs in a thread, it can be terminated anywhere and run other code in another thread.
Read more about it
- -number – This is a function
- Automatic type conversion
- Infix operators in JavaScript
- Do you know what JavaScript Typeof is?
- Learn a few representative events in JavaScript
- Learn to Understand client-side JavaScript- Event Classification (part 1)
- Client-side JavaScript- Event Classification (2)
carry on
Learning, recording and accumulating is a long process!
Buy Less by Know More! Calm Down! Come on!