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

Mar 20, 2017 pm 04:10 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is apache server? What is apache server for? What is apache server? What is apache server for? Apr 13, 2025 am 11:57 AM

Apache server is a powerful web server software that acts as a bridge between browsers and website servers. 1. It handles HTTP requests and returns web page content based on requests; 2. Modular design allows extended functions, such as support for SSL encryption and dynamic web pages; 3. Configuration files (such as virtual host configurations) need to be carefully set to avoid security vulnerabilities, and optimize performance parameters, such as thread count and timeout time, in order to build high-performance and secure web applications.

Understanding H5 Code: The Fundamentals of HTML5 Understanding H5 Code: The Fundamentals of HTML5 Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

Is H5 a Shorthand for HTML5? Exploring the Details Is H5 a Shorthand for HTML5? Exploring the Details Apr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

Tips for using HDFS file system on CentOS Tips for using HDFS file system on CentOS Apr 14, 2025 pm 07:30 PM

The Installation, Configuration and Optimization Guide for HDFS File System under CentOS System This article will guide you how to install, configure and optimize Hadoop Distributed File System (HDFS) on CentOS System. HDFS installation and configuration Java environment installation: First, make sure that the appropriate Java environment is installed. Edit /etc/profile file, add the following, and replace /usr/lib/java-1.8.0/jdk1.8.0_144 with your actual Java installation path: exportJAVA_HOME=/usr/lib/java-1.8.0/jdk1.8.0_144exportPATH=$J

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Nginx performance monitoring and troubleshooting tools Nginx performance monitoring and troubleshooting tools Apr 13, 2025 pm 10:00 PM

Nginx performance monitoring and troubleshooting are mainly carried out through the following steps: 1. Use nginx-V to view version information, and enable the stub_status module to monitor the number of active connections, requests and cache hit rate; 2. Use top command to monitor system resource occupation, iostat and vmstat monitor disk I/O and memory usage respectively; 3. Use tcpdump to capture packets to analyze network traffic and troubleshoot network connection problems; 4. Properly configure the number of worker processes to avoid insufficient concurrent processing capabilities or excessive process context switching overhead; 5. Correctly configure Nginx cache to avoid improper cache size settings; 6. By analyzing Nginx logs, such as using awk and grep commands or ELK

How to configure HTTPS server in Debian OpenSSL How to configure HTTPS server in Debian OpenSSL Apr 13, 2025 am 11:03 AM

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

How to monitor HDFS status on CentOS How to monitor HDFS status on CentOS Apr 14, 2025 pm 07:33 PM

There are many ways to monitor the status of HDFS (Hadoop Distributed File System) on CentOS systems. This article will introduce several commonly used methods to help you choose the most suitable solution. 1. Use Hadoop’s own WebUI, Hadoop’s own Web interface to provide cluster status monitoring function. Steps: Make sure the Hadoop cluster is up and running. Access the WebUI: Enter http://:50070 (Hadoop2.x) or http://:9870 (Hadoop3.x) in your browser. The default username and password are usually hdfs/hdfs. 2. Command line tool monitoring Hadoop provides a series of command line tools to facilitate monitoring

See all articles