Home Web Front-end JS Tutorial A brief analysis of the setTimeou thread mechanism

A brief analysis of the setTimeou thread mechanism

Sep 09, 2017 am 09:16 AM
firefox settimeout webkit

When I read the book High Performance JavaScript, I saw this sentence:

Putting scripts at the top of the page in this way typically leads to a noticeable delay, often in the form of a blank white page, before the user can even begin reading or otherwise interacting with the page.

The explanation is as follows:

Placing the script script in the head will cause a significant delay, usually as follows: The page opens blank and the user cannot read or interact with it.

My understanding is: putting js in the head, the loading and execution of js causes page rendering to be delayed. If js is placed at the end, since the page rendering precedes the loading or execution of js, it can be presented to the user first without being affected by the blocking of js.

In order to verify, the following experiment was done:

<p>hello world</p><script type="text/javascript">  
    function f() {    
    var t = +new Date();

    //运行5秒    while(true) {
      if(+new Date() - t > 5) {
        break;
      }
    }
  }
  f();  // ①</script>
Copy after login

The experimental results are interesting: hello world waited for 5 seconds before it came out.

In-depth verification: Introduce the above script as a js external link or load it dynamically. The result still came out after waiting for 5 seconds.

This means that the rendering of the page must occur only after all js are loaded and executed. There is something wrong with the above paragraph.

Does this mean that as long as js does not involve dom operations, placing it at the head and tail will have the same effect? of course not. For example, when there are pictures or other resources in the html, if js is placed at the head, the download of the picture needs to wait until js is finished running before starting. However, if js is placed at the tail, since the download of the picture does not block the running of js, you can Achieve parallel downloading of images and running of js.

Is this the end of the problem? Of course not. A very important part of front-end work is performance optimization. How to optimize the above js? So I thought of setTimeout.

setTimeout is used to delay the execution of js code. It has the advantage that it will not block the execution of js behind it. So I guess setTimeout will also not block the rendering of the page.

Option 1: Replace the ① part above with:

 setTimeout(f,0);
Copy after login

As a result, hello world still has to wait for 5 seconds before it comes out. But if you are careful, you will find that the load symbol on the browser label is missing.

Continue to guess, 0 is too small, causing the browser to find that there is no js code behind setTimeout and immediately execute the content in setTimeout, that is, the f function. So change the time to 100ms.

Option 2: Replace the ① part above with:

setTimeout(f, 100);
Copy after login

The result is hello world pops up instantly. A little excited. Interested students can continue testing. At this time, you will find that there will be a critical value (different browsers have different critical values). When the second parameter of setTimeout is greater than this critical value, hello world will pop up instantly. Otherwise, you need to wait. It will pop up after the function inside is completed.

It’s amazing, why does this happen? To answer this question, we must study the browser's threading mechanism.

We know that there are at least two threads inside the browser: the thread that parses js and the thread that renders the interface. Here we temporarily call them JS thread and UI thread.

Since js can manipulate the DOM, if you modify the properties of these elements while rendering the interface (that is, the JS thread and the UI thread run at the same time), the element data obtained before and after the rendering thread may be inconsistent. Therefore, in order to prevent unpredictable rendering results, the browser controls the JS thread and the UI thread to execute synchronously in a queue.

Back to the above question, when setTimeout is executed, a new timer thread will be opened. This is exactly when the JS thread is running. When the JS thread is completed, it is found that setTimeout will start executing immediately (that is, the time is less than The above critical value), in order to avoid the bad experience caused by the serious delay of setTimeout caused by the UI thread running for too long, the browser chooses to wait until setTimeout expires, and then runs the js inside. If it is found that setTimeout will take a long time to expire, in order to avoid wasting time, the browser chooses to switch to the UI thread immediately.

Conclusion: setTimeout can be used to process time-consuming js code, but be careful not to set the second parameter too small, otherwise you will see the same blank page. It is recommended to be around 100ms, which can satisfy all browsers. Of course, if you can't be compatible with IE, abandon setTimeout and web workers will be a good choice.

In HTML4, programs created by js are single-threaded. Web Workers are new in HTML5 and are a technology used to implement background processing in web applications. It is very easy to create a thread running in the background using this API:

var worker = new Worker(&#39;*.js&#39;);// 后台线程是不能访问页面或窗口对象的// 但可通过发送消息和接受消息与后台线程传递数据worker.onmessage = function (e) {};
worker.postMessage = function (e) {};
Copy after login

The above is the detailed content of A brief analysis of the setTimeou thread mechanism. 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)

How to remove Firefox Snap in Ubuntu Linux? How to remove Firefox Snap in Ubuntu Linux? Feb 21, 2024 pm 07:00 PM

To remove FirefoxSnap in Ubuntu Linux, you can follow these steps: Open a terminal and log in to your Ubuntu system as administrator. Run the following command to uninstall FirefoxSnap: sudosnapremovefirefox You will be prompted for your administrator password. Enter your password and press Enter to confirm. Wait for command execution to complete. Once completed, FirefoxSnap will be completely removed. Note that this will remove versions of Firefox installed via the Snap package manager. If you installed another version of Firefox through other means (such as the APT package manager), you will not be affected. Go through the above steps

What is the difference between settimeout and setinterval What is the difference between settimeout and setinterval Aug 15, 2023 pm 02:06 PM

The difference between settimeout and setInterval: 1. Trigger time, settimeout is one-time, it executes the function once after setting the delay time, while setinterval is repetitive, it will execute the function repeatedly at the set time interval; 2. Execution times, settimeout is only executed once, and setinterval will be executed repeatedly until canceled.

Can mozilla firefox be uninstalled? Can mozilla firefox be uninstalled? Mar 15, 2023 pm 04:40 PM

Mozilla Firefox can be uninstalled; Firefox is a third-party browser and can be uninstalled if it is not needed. Uninstallation method: 1. In the Start menu, click "Windwos System" - "Control Panel"; 2. In the "Control Panel" interface, click "Programs and Features"; 3. In the new interface, find and double-click Firefox Browser icon; 4. In the uninstall pop-up window, click "Next"; 5. Click "Uninstall".

Firefox 113 new features: support for AV1 animations, enhanced password generator and picture-in-picture features Firefox 113 new features: support for AV1 animations, enhanced password generator and picture-in-picture features Mar 05, 2024 pm 05:20 PM

According to recent news, while Mozilla released the stable version of Firefox 112, it also announced that the next major version, Firefox 113, has entered the Beta channel and supports AV1 animations, enhanced password generator and picture-in-picture features. The main new functions/features of Firefox 113 are as follows: Support for AV1 format animated images (AVIS); Enhance the security of the password generator by introducing special characters; Enhance the picture-in-picture function, support rewind, display video time, and enable full screen more easily Mode provides official DEB installation files for Debian and Ubuntu distributions. Updated bookmark import feature, icons for imported bookmarks are supported by default. Hardware accelerated AV1 video decoding is enabled by default on supported hardware using w

How to use Mozilla Firefox in Scrapy to solve the problem of scanning QR code to log in? How to use Mozilla Firefox in Scrapy to solve the problem of scanning QR code to log in? Jun 22, 2023 pm 09:50 PM

For crawlers to crawl websites that require login, verification code or scan code login is a very troublesome problem. Scrapy is a very easy-to-use crawler framework in Python, but when processing verification codes or scanning QR codes to log in, some special measures need to be taken. As a common browser, Mozilla Firefox provides a solution that can help us solve this problem. The core module of Scrapy is twisted, which only supports asynchronous requests, but some websites require the use of cookies and

Apple releases update to fix WebKit vulnerability and excessive power consumption in MacBook Apple releases update to fix WebKit vulnerability and excessive power consumption in MacBook Apr 15, 2023 am 10:49 AM

Apple has released updates for iPhone, iPad, Mac and Apple Watch. Although the updates for each device are small, they address WebKit vulnerabilities. The company also assured that it has fixed a bug that caused MacBook laptops to unexpectedly drain their batteries. Apple iOS and iPadOS 15.3.1 are minor updates. It doesn't actually contain any major features. However, it is useful for people using braille displays. Additionally, the update resolves an arbitrary code execution vulnerability. The update notes for iOS 15.3.1 mention: iOS 15.3.1 provides important security updates for your iPhone and fixes

Ubuntu 23.10 will run Firefox in native Wayland mode by default Ubuntu 23.10 will run Firefox in native Wayland mode by default Feb 29, 2024 am 10:10 AM

Canonical recently announced that in the upcoming Ubuntu 23.10, Firefox Snap has been configured to run in Wayland mode by default. Note: Ubuntu currently has the Wayland session by default, and Firefox can also work normally. However, currently FirefoxSnap actually runs in XWayland compatibility mode, rather than the strict native Wayland mode. Canonical announced that it will run the Firefox browser in Wayland mode by default, so that problems such as interface blur and scaling distortion will not occur on HiDPI displays, and it will support touch gestures such as dragging and pinching. As mentioned above, Ubunt

Europe allows Apple to relax browser restrictions: Non-WebKit engines can be selected, Chrome can be used as the default browser Europe allows Apple to relax browser restrictions: Non-WebKit engines can be selected, Chrome can be used as the default browser Jan 26, 2024 am 10:42 AM

According to news on January 26, after iPhone users in Europe upgrade to the iOS17.4Beta1 update, they will see a new window after opening the Safari browser, which supports changing the default browser. Users in Europe can set up non-Safari browsers including Firefox, Opera, Chrome, Brave and Microsoft Edge according to their own preferences. Browser apps can now also use browser engines other than WebKit, including browser apps and in-app browsing experiences. Apple previously required that all browsers on iOS, including common browsers such as Chrome and Firefox, must use the WebKit engine.

See all articles