javascript Worker Tutorial

javascript Worker Tutorial

Article directory

Generally, if you encounter a scene with a large amount of calculation and high memory usage, you should consider using javascript Worker, which changes javascript from single-threaded to multi-threaded.

Its biggest advantage is that it avoids page jams caused by a large number of calculations through multi-threading. Let's look at the example below.

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>hello world</h1>
    <input type="text">
    <script>
        let a = 1000000;
        for (let i = 0; i < a; i++) {
    
    
            console.log(i);
        }
    </script>

</body>

</html>

When you open this file, the page will freeze and the user cannot enter any content, resulting in a very bad user experience.

Using Worker is also very simple, as follows:

First, we need to determine whether the browser supports Worker.

 if (window.Worker) {
    
    
 	// ........
 }

Then create a new file worker.js with the following content:

let a = 1000000;
for (let i = 0; i < a; i++) {
    
    
    console.log(i);
}
postMessage('执行完毕')

Then call Worker in our index.html :

        // 检测是否支持worker
        if (window.Worker) {
    
    
            var myWorker = new Worker('./worker.js');
            myWorker.onmessage = function (e) {
    
    
                console.log('接收到消息:', e);
            }
        }

Refresh the index.html page to execute, and you can find that the page is not stuck, even if the calculation is heavy.

Execution method:

index.html

title content
Send a message myWorker.postMessage()
receive message myWorker.onmessage=()=>{}
termination myWorker.terminate()

worker.js

Send a message receive message
Send a message postMessage()
receive message onmessage=()=>{}
termination close()

Although it is good to use Worker, its compatibility still needs to be considered.

Guess you like

Origin blog.csdn.net/qq_41974199/article/details/130649500