


html5 WebWorkers sample code sharing to prevent browser from suspended animation
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>
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>
calculate.js
onmessage = function(event){ var num = event.data; var result = 0; for(var i = 0; i<num;i++){ result += i; } postMessage(result); };
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!

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.