preface
Hello, everyone, I am Lin Sanxin. It is my motto to talk about the most difficult knowledge points in the most easy-to-understand words. The basis is that the prerequisite for progress is my original aspiration
Why is JS a single-threaded language?
So why is JavaScript a single threaded language? As we all know, JavaScript is a front-end language, and the front-end stage is the browser, and what does the browser do to please the user? You pass through a page of DOM nodes one by one. In the end, JavaScript is all about the quality of the page.
JavaScript is designed as a single-threaded language for pages. Let’s assume that JavaScript is a multi-threaded language. If thread 1 is modifying the DOM node and thread 2 is also modifying the same DOM node, who should the page listen to? This creates conflicts, which are not allowed in front of the user, so JavaScript is designed as a single-threaded language, and everything you want to do has to be done sequentially.
Web Worker?
background
As mentioned earlier, JavaScript is a single-threaded language, which causes a lot of problems. I don’t know if you have encountered such a thing when developing: processing a super large data, resulting in the entire code logic blocked for a period of time
Here’s what HAPPENED to me:
- 1. It takes a short period of time to upload large file slices with hash
- 2, tree data front-end processing, need to process a short period of time
And what kind of fake death problem might that cause?
- 1. Blocking of page rendering
- 2. Blocking of subsequent code execution
What is?
Web workers are a new technology developed to solve the problem of browser death. It’s a multithreaded model, which is also host-based. It is a child thread of the JavaScript thread and is completely controlled by the main thread, but you cannot manipulate the DOM in a Web Worker. The DOM needs to be unique, so the main tone cannot be changed, but a new thread is needed to share the complex computing tasks, which is the Web Worker
Compatibility:
Web workers have the following characteristics:
- 1. Once created, it will not be interrupted by the main thread. The Web Worker is still running even if the main thread freezes
- 2. Web workers are also restricted by the same-origin policy, so same-origin pages can only be accessed
- 3. Do not operate and access DOM. As mentioned above, multi-threaded DOM manipulation is easy to cause conflicts, so it is prohibited
- 4. Do not use global interactive methods (alert, confirm, etc.). Other global methods can be used basically
- 5. Cannot read local files (in fact, the browser itself forbids JavaScript to read local files for security reasons)
- 6. Worker threads and main threads do not share scope and resources
- 7. There are two types of Web workers:
Dedicated Web Worker
: dedicated thread that can only be used within a web pageShared Web Worker
Shared threads, which can be shared across multiple homologous web pages, are also a means of cross-page communication
Use the Web Worker
scenario
To show you what a Web Worker looks like, I’ve created a few new files
// index.html
<script src="./index.js"></script>
<img src=". / avatar. JPG" alt="">
Copy the code
// index.js
console.time('Data processing time')
// Data processing
function handleData(num) {
for (let i = 0; i < num; i++) {
let str = ' '
while (str.length < 150) {
str += 'ah'
}
}
}
handleData(2000000)
console.timeEnd('Data processing time')
Copy the code
Let’s take a look at how much time it takes to process the data:
Render the image after this time (render the image also takes a certain amount of time, so there is a difference), which also indicates that the data processing just now, blocked the page rendering:
Basic use of Web Worker
Dedicated Web workers are often used in project development, so let’s talk about the basic use of this
Rewrite the code in index.js
// index.js
// Instantiate a Woeker and pass in the path to the object file that will generate a worker thread
const worker = new Worker("data.js")
// Use postMessage to transfer information to the target file
worker.postMessage(2000000)
// Use onMessage to receive messages
worker.onmessage = (e) = > {
console.log(e.data)
};
// Use onError for the object file, which specifies the callback to the worker thread when an error occurs
worker.onerror = function (e) {
console.log("error at " + e.filename + ":" + e.lineno + e.message)
};
Copy the code
Then we create the object file data.js, which will generate a worker thread
// Use importScripts to reference files, urls, local JS files
importScripts('xxxxxxx')
// importScripts(' XXXXXXX ', 'XXXXXXXX ') can also be passed multiple times
// Data processing
function handleData(num) {
for (let i = 0; i < num; i++) {
let str = ' '
while (str.length < 150) {
str += 'ah'
}
}
}
onmessage = async (e) => {
console.time('Data processing time')
const res = handleData(e.data)
postMessage('Done with')
console.timeEnd('Data processing time')}Copy the code
The effect
Let’s take a look at the code and render again and compare it to what we saw at the beginning:
Image rendering is not blocked either:
Cancel the process
You can end the process using the Terminate method
worker.onmessage = (e) = > {
// Terminate the specified worker process immediately if an error is reported
worker.terminate()
console.log(e.data)
}
Copy the code
Personal understanding
In fact, Web workers do not change the fact that JavaScript is single threaded per se, it relies on multi-threading in the browser
conclusion
I am Lin Sanxin, an enthusiastic front-end novice programmer. If you progress, like the front end, want to learn the front end, then we can make friends, touch fish ha ha, touch fish, point this –> touch fish boiling point