Home > Web Front-end > H5 Tutorial > html5 WebWorkers sample code sharing to prevent browser from suspended animation

html5 WebWorkers sample code sharing to prevent browser from suspended animation

黄舟
Release: 2017-03-20 16:10:30
Original
1720 people have browsed it

During web development, it is often encountered that the browser does not respond to events and enters a state of suspended animation, or even pops up a prompt box of "Script running time is too long". If this happens, it means that your script is out of control.

A browser has at least three threads: js engine thread (processing js), GUI rendering thread (rendering page), and browser event trigger thread (controlling interaction).

1: JavaScript engine is based on event-driven single-thread execution. The JS engine has been waiting for the arrival of tasks in the task queue and then processes them. No matter how the browser There is only one JS thread running the JS program at any time.

2: The GUI rendering thread is responsible for rendering the browser interface. When the interface needs to be redrawn (Repaint) or a reflow is caused by some operation, this thread will be executed. However, it should be noted that the GUI rendering thread and the JS engine are mutually exclusive. When the JS engine is executed, the GUI thread will be suspended, and GUI updates will be saved in a queue and executed immediately when the JS engine is idle.

3: Event triggering thread. When an event is triggered, the thread will add the event to the end of the pending queue and wait for processing by the JS engine. These events can come from the code block currently executed by the JavaScript engine such as setTimeOut, or from other threads in the browser kernel such as mouse clicks, AJAX asynchronous requests, etc. However, due to the single-threaded relationship of JS, all these events have to be queued for processing by the JS engine.

After understanding the browser's kernel processing method, it is not difficult to understand why the browser enters a state of suspended animation. When a JS script occupies the processor for a long time, the browser's GUI update will be suspended, and the subsequent Event responses are also queued and cannot be processed, causing the browser to be locked into a state of suspended animation. In addition, DOM operations are performed in JS scripts. Once the JS call is completed, a GUI rendering will be performed immediately before starting the next task. Therefore, a large number of DOM operations in JS will also cause slow event response or even truly freeze the browser, such as Insert a lot of HTML at once in IE6. And if the prompt box "Script running time is too long" pops up, it means that your JS script must have an infinite loop or perform too deep a recursive operation.

Now if we encounter this situation, we can do more than just optimize the code. HTML5 webWorkers provides a js background processing thread API, which allows complex and time-consuming simple js logic processing to be placed in Processing is performed in the browser background thread so that the js thread does not block the rendering of the UI thread. This thread cannot interact with the page, such as getting elements, alerts, etc. Data can also be transferred between multiple threads through the same method.

Look at the code directly:

Example: The user inputs a number and performs addition (+=)

Previous approach:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>webworkers--calculate</title>
</head>
<body>
    <input id="num" name="num" type="text"/>
    <button onclick = "calculate()">计算</button><br />
    <div id="result" style="color:red;"></div>
    <div id="time" style="color:red;"></div>
    <script type="text/javascript" src="calculate.js"></script>
    <script type="text/javascript">
        function calculate(){
            data1 = new Date().getTime();
            var num = document.getElementById("num").value;
            var val = parseInt(num,10);
            var result =0;
            for(var i =0; i<num;i++){
                result += i;
            }
            data2 = new Date().getTime();
            document.getElementById("result").innerHTML ="计算结果:"+result;
            document.getElementById("time").innerHTML ="普通 耗时:"+ (data2 - data1)+"ms";
        }
    </script>
</body>
</html>
Copy after login

After using webWorkers :

calculate.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>webworkers--calculate</title>
</head>
<body>
    <input id="num" name="num" type="text"/>
    <button onclick = "calculate()">计算</button><br />
    <div id="result" style="color:red;"></div>
    <div id="time" style="color:red;"></div>
    <script type="text/javascript" src="calculate.js"></script>
    <script type="text/javascript">
        var worker = new Worker("calculate.js");
        var data1 =0;
        var data2 =0;
        worker.onmessage = function(event){
                var data = event.data;
                data2 = new Date().getTime();
                document.getElementById("result").innerHTML ="计算结果:"+data;
                document.getElementById("time").innerHTML ="workers 耗时:"+ (data2 - data1)+"ms";
            };
         function calculate(){
            data1 = new Date().getTime();
            var num = document.getElementById("num").value;
            var val = parseInt(num,10);
            worker.postMessage(val);
        }
    </script>
</body>
</html>
Copy after login

calculate.js

onmessage = function(event){
    var num = event.data;
    var result = 0;
    for(var i = 0; i<num;i++){
        result += i;
    }
    postMessage(result);
};
Copy after login

webWorker needs to put the code into the web server. If you are using localhost, please use a higher version of the chrome browser Open, the firefox browser will display the error "Could not get domain!" when processing localhost.

Comparing the above two implementation methods, when calculating When the value reaches 10 billion, the normal method takes a long time and usually gets stuck.

The effect of webWorkers under Chrome15. Correction: getTime() should return milliseconds (ms), not seconds (s).

The effect of ordinary methods under Chrome15

It can be seen that webWorkers are still very valuable in future web applications.

The above is the detailed content of html5 WebWorkers sample code sharing to prevent browser from suspended animation. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template