Closure classic case of anti-shake and throttling

3.1 if you

Returns the directory

Below we have a small anti – shake case code.

If you have a computer and you’re interested in thinking about what anti-shake is. Copy the code to your browser, try clicking the button, and look at the Console to see how the Console prints.

If you don’t have a computer, let’s take a look at the code implementation and watch the GIF demo below. (This effect is not as straightforward and effective as their own)

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" The content = "width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no" > < meta HTTP - equiv = "X-ray UA - Compatible" Content ="ie=edge"> <title> </head> <body> <button ID ="debounce"> </button> <script> window.onload = function() {var myDebounce = document.getelementById ("debounce"); myDebounce.addEventListener("click", debounce(sayDebounce)); } function debounce(fn) {// create a timer for the return value of the timer let timeout = null; Return function() {// each time the user clicks/input, clear the previous timer clearTimeout(timeout); // Then create a new setTimeout, // this will ensure that the interval after clicking the button // if the user still clicks, Timeout = setTimeout(() => {fn.call(this, arguments); }, 1000); }; } function sayDebounce() {//... For some tasks that need to be handled, execute console.log(" Handled successfully!" ); } </script> </body> </ HTML > Copy the codeCopy the code

Good, I believe you have looked at the code, let’s look at the demo:

At this point, we can throw out the concept of anti-shake:

  • If a task is triggered frequently, the task is executed only when the task triggering interval exceeds the specified interval.

Combining the above code, we can see that after the click event is triggered, if the user clicks again, we will empty the previous timer and create a new timer. This will have to wait, and if you keep pushing, I’ll reset the clock!

Empty talk is of no use.

  • There’s an input box that calls the interface for associative words. However, because it is not good to call the interface frequently, we use the anti-shake function in the code, and only after a period of time after the user input, the interface will be called and associative words will appear.

Friends can try to look at the above case, first to realize the solution of this scene, if the feeling is not good, then see: “Anti-shake and throttling application scenario and implementation”

What is arguments? Arguments can be used as a tool to implement overloaded functions. Then, let’s take an example: In function test(), since we are not sure how many variables there are, such as test(“jsliang”, 24), or test(“LiangJunrong”, “jsliang”, “24”), Just accept arguments in the test function. In function test() {let arr1 = argument[0]}, arr1 gets the first variable passed in. So, fn.call(this, arguments) is actually replacing an indeterminate variable with a function.

Reference 1: the Use of Apply and Call in JS

3.2 the throttle

Returns the directory

Finish shaking, let’s talk about throttling, rules will not say, first on the code:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" The content = "width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no" > < meta HTTP - equiv = "X-ray UA - Compatible" Content ="ie=edge"> <title> </title> </head> <body> <button ID ="throttle"> </button> <script> window.onload = function() {var myThrottle = document.getelementbyid ("throttle"); myThrottle.addEventListener("click", throttle(sayThrottle)); } function throttle(fn) {// 4, let canRun = true; Return function() {return function() {return function() {return function(); canRun) { return; } // set canRun to false to prevent the execution of canRun = false; // 7, timer setTimeout(() => {fn. Call (this, arguments); CanRun = true; canRun = true; canRun = true; canRun = true; }, 1000); }; } function sayThrottle() {console.log(" Throttled successfully!" ); } </script> </body> </ HTML > Copy the codeCopy the code

Very well, after looking at the code partners should be roughly clear about what is going on, let’s look at the GIF implementation:

After looking at the code and GIF implementation, we can see that throttling is:

  • Throttling: Only one task will be executed at a specified time interval.

So, throttling at work?

  1. Lazy loading to listen to calculate the scrollbar position, using throttling at a frequency of a certain amount of time.
  2. The user clicks the submit button, assuming we know the approximate return time of the interface, and we use throttling to only allow one click in a certain amount of time.

In this way, in certain work scenarios, we can use anti-shake and throttling to reduce unnecessary loss.

Now the question is, assuming your interviewer hears you say this, will he or she follow up by asking, “Why is that scenario too costly?”

OK, that’s where the browser renders the page…

Quadruple draw and reflow

Returns the directory

Before we talk about browsers rendering pages, we need to understand two things. One is called browsers parsing urls, and the other is redraw and reflow, which is covered in this section:

  • Repaint: The browser uses repaint to update elements when the change in style does not affect the layout, with less loss because only the re-pixelation at the UI level is required.

Common redraw operations are:

  1. Change the color of the element
  2. Change the element background color
  3. More……
  • Reflow: also known as layout. When an element’s size, structure, or trigger certain attributes, the browser rerenders the page, called backflow. In this case, the browser needs to recalculate, and after the calculation, the page layout needs to be rearranged, so it is a heavy operation.

Common backflow operations are:

  1. Page first render
  2. The browser window size changes
  3. Element size/position/content changed
  4. Element font size changes
  5. Add or remove visible DOM elements
  6. Activate CSS pseudo-classes (:hover…)
  7. More……
  • Important: Backflow must trigger redraw, redraw does not necessarily trigger backflow. The cost of redrawing is low and the cost of backflow is high.

You may be a little confused by this. You just told me about anti-shake and throttling. Why did you jump to redraw and reflux?

OK, to keep you in suspense, let’s look at the following scenario:

  • There is a div box on the interface, the user can input some information of the DIV box in the input box, such as width, height, input finished immediately change the attribute. However, because changes are stored in the database at any time, you need to invoke the interface. If left unchecked…

The reason for throttling is that there are some things that cause browser backflow, and backflow causes browser overhead, so we use throttling to prevent things that increase browser overhead.

To illustrate graphically:

In this way, we can vividly remember the combination of anti-shake and throttling with redrawing and reflux.

So how can we avoid heavy use of redraw and reflow in our work? :

  1. Avoid frequent operation styles, you can modify them all at once
  2. Try to use class for style modification rather than manipulating styles directly
  3. Reduce DOM manipulation by using string insertions at once

OK, now that we’ve covered the two parts, the question arises again: “Is there repainting and reflow during browser rendering?” “What happens between the time the browser enters the URL and the time the rendering succeeds?”

Let’s explore further…

Browsers parse URLS

Returns the directory

To make our level of knowledge seem more profound, we should consider the following two questions:

  • What happens between the time the browser enters the URL and the time the rendering succeeds?
  • What happens when the browser renders, does it redraw and reflow?

When the user enters the URL and the browser presents the page to the user, the following process takes place:

  • A version of A:
  1. The user enters the URL address.
  2. Perform DNS domain name resolution for URL addresses.
  3. Establish a TCP connection (three-way handshake).
  4. The browser sends an HTTP request packet.
  5. The server returns an HTTP response packet.
  6. Close the TCP connection (wave four times).
  7. The browser parses the document resources and renders the page.

At this point, I suddenly remembered a dialogue:

Student: “Sir, what are the test points of this course?”

Teacher: “all is the key!”

enm… I don’t know if the teacher will be beaten or not, but I do know if jsliang will be punished if written in this way. Therefore, let’s use the picture above to further outline our structure:

Very good, Jsliang feels that his drawing skills are one step forward ~

① : Although I am very grateful that there are so many articles on the Internet to refer to, but after I checked about twenty articles, Jsliang felt that there are nine out of ten problems in this part, I asked my friends, some of them said right, some said wrong. However, do not prevent small partners continue to see ha. ② : In order to avoid problems, here is another version, friends can say which version you support in the comments section:

  • Version B
  1. The user enters the URL address.
  2. Perform DNS domain name resolution for URL addresses.
  3. The TCP connection is enabled.
  4. Requests and responses to HTTP packets.
  5. The browser parses the document resources and renders the page.

Here we can clearly understand the process from the user entering the URL to the browser rendering the page to the user.

So the rest is simple:

  1. What is DNS resolution and how does it flow?
  2. What is the TCP three-way handshake and what is the TCP four-way wave, and how do they flow?
  3. How does the browser parse document resources and render pages?

Let’s go through the following three points step by step.

Reference 1: “The Whole process of Web page parsing (Input URL to display page)” Reference 2: “Analysis of browser Rendering page Process”

6 DNS Domain name resolution

Returns the directory

First, let’s tackle the first question:

  • What is DNS resolution and how does it flow?

The Domain Name System (DNS) is an abbreviation of the Domain Name System (DNS). The DNS service is used to convert host and Domain names into IP addresses:

Domain name: http://jsliang.top < – > DNS < – > IPV4:119.147.15.13

IPV4 is faked, and is used only to indicate that the DNS can return an IP address after resolution

So, when a user types http://jsliang.top in a browser, DNS goes through the following steps:

  1. The browser looks up DNS resolution records in its cache based on the address. If yes, the IP address is returned. If no, check whether the hosts file in the operating system has DNS resolution records of the domain name.
  2. If no DNS resolution record of the domain name is found in the browser cache or the hosts file of the operating system in condition 1, or the domain name has expired, the system sends a request to the DNS server to resolve the domain name.
  3. Request the local DNS server to resolve the domain name. If the resolution fails, request the root DNS server to resolve the domain name.
  4. The root server returns a primary DNS server to the local DNS server.
  5. The local DNS server sends a resolution request to the active DNS server.
  6. After receiving the resolution request, the primary DNS server searches for and returns the DNS server address corresponding to the domain name.
  7. The DNS server queries the mapping table between domain names and IP addresses and returns the destination IP address record and a TTL value.
  8. The local DNS server receives IP and TTL values and caches them. The cache duration is controlled by the TTL value.
  9. The domain name resolution result is returned to the user and cached in the local system cache based on the TTL value. The domain name resolution process is complete.

Reading text is always difficult to understand, follow jsliang to draw a picture through, it will feel clear:

Seven TCP three handshake and four wave

Returns the directory

Then, we tackle the second problem:

  • What is the TCP three-way handshake and what is the TCP four-way wave, and how do they flow?

What is TCP? Transmission Control Protocol (TCP) is a connection-oriented, reliable, byte stream – based transport layer communication Protocol.

In simple terms, it is used to reliably transfer data streams from one host to another.

As for how it works, I won’t get into that for now, but we just want to know two things: three handshakes and four waves.

  • Three handshakes:
  1. First handshake: At first, both ends are CLOSED. The Client sets the SYN flag bit to 1 and randomly generates a valueseq = xAnd sends the packet to the Server. The Client enters the SYN-sent state and waits for confirmation from the Server.
  2. Second handshake: Indicates the flag bit of the Server after receiving data packetsSYN = 1When the Client requests to establish a connection, the Server sets the flag bit SYN and ACK to 1.ack = x + 1, randomly generating a valueseq = yAnd sends the packet to the Client to confirm the connection request, and the Server entersSYN-RCVDState, when the operating system allocates the TCP cache and variables for the TCP connection.
  3. Third handshake: After receiving the confirmation, the Client checks whether the SEQ isx + 1Is ACK 1? If yes, set the flag bit ACK to 1.ack = y + 1And the operating system allocates the TCP cache and variables for the TCP connection and sends the packet to the Server. The Server checks whether the ACK isy + 1If yes, the connection is established successfully. The Client and Server enter the Established state and complete the three-way handshake. Then the Client and Server can start data transmission.

Text too messy, show you picture:

  • Four waves:
  1. First wave: The application process of the Client sends a connection-release packet segment to its TCP (FIN = 1And the serial numberseq = u), stops sending data again, actively closes the TCP connection, and enters the FIN-WaIT-1 state, waiting for the confirmation from the Server.
  2. Second wave: The Server sends an acknowledgement packet after receiving the connection release packet.ACK = 1And confirm,ack = u + 1And the serial numberseq = v), the Server enters close-wait state. In this state, TCP is half-closed and the connection between the Client and the Server is released.

Note: After receiving the confirmation from the Server, the Client enters the FIN-WaIT-2 state and waits for the connection release packet sent by the Server.

  1. Third wave: The Server has no data to send to the Client. The Server sends a connection-release message segment (FIN = 1.ACK = 1And the serial numberseq = wAnd confirm,ack = u + 1), the Server enters the last-ACK state and waits for the confirmation from the Client.
  2. Fourth wave: After receiving the connection release packet from the Server, the Client sends an acknowledgement packet (ACK = 1.seq = u + 1.ack = w + 1), and the Client enters the time-wait state. In this case, TCP is not released and the Client enters the CLOSED state only after the time set by the timer is 2MSL.

Text too messy, show you picture:

! [

](C:%5CUsers%5Clenovo%5CDesktop%5CMarkdown%5C1697220a338c7f9b.png)

OK, so now we understand TCP and its three handshakes and four hand waves. Jsliang has made a short story for you to remember.

  • Three handshakes + four waves
  1. Jsliang :(initiates a wechat friend request to the girl) “hello, can I friend you?” — The first handshake
  2. Girl :(approved) “hello, nice to meet you ~” — second handshake
  3. Jsliang: “Hello, I call Liang Junrong, front end toss small expert……” — The third handshake
  4. … (Chat content)
  5. ………………… (Chat content)
  6. ……………………… (Chat content)
  7. ………………… (Chat content)
  8. … (Chat content)
  9. Jsliang :(cold took a picture of paper towel basket) “ah, very uncomfortable today.” — First wave
  10. Girl: “Oh my God, you’re gross!” — Second wave
  11. Sister: “the za still be do not know, mutually deleted, thank!” — Third wave
  12. Jsliang: “No, you listen to me!” — Fourth wave
  13. Girl :(deletes friend) — CLOSED
  14. Jsliang: (! “I caught a cold today.” Girl turned on friend verification, and you’re not her friend. Please send a friend verification request first, after the verification of the other party, can chat. – CLOSED

OK, successful embarrassing, I believe partners have a good understanding.

So, let’s keep exploring.

Reference 1: TCP Three-way handshake and Four-way Wave Process Reference 2: TCP three-way handshake and four-way Wave process

Browsers render pages

Returns the directory

Finally, we tackle the third question:

  • How does the browser parse document resources and render pages?

Without further ado, let’s see:

  1. The browser uses HTMLParser to parse HTML into DOM Tree based on the principle of deep traversal.
  2. The browser uses CSSParser to parse CSS into CSS Rule Tree (CSSOM Tree).
  3. The browser parses the JavaScript code through the DOM API or the CSSOM API and applies it to the layout, rendering the results of the response as required.
  4. Construct render Tree according to DOM Tree and CSSOM Tree.
  5. Layout: When the geometry of any node in the Render Tree changes, it rearranges the render Tree, recalculating the position of all nodes on the screen.
  6. Render Tree repaint: Render Tree repaints when any element style attribute (geometry unchanged) changes, such as font color, background, etc.
  7. Paint: Iterate over the Render Tree and invoke the hardware graphics API to draw each node.

The text explanation is definitely not clear enough, but Jsliang is tired of drawing several pictures, so we stole a picture:

This way, we know exactly how the browser renders the page

Reference: “One Article to Nail a front-end interview”

Nine summary

Returns the directory

So, what did we do?

  1. We were running into some problems at work that were jamming the page, so we looked it up and realized that if we wanted to reduce browser overhead, we needed to use anti-shake and throttling.
  2. After solving the problem with anti-shake and throttling, we wondered why, so we took a closer look at redraw and reflux.
  3. Redraw and backflow only tell us how the browser renders on CSS. We need to learn more about how the browser renders the page, but the onion is peeled off layer by layer, so we need to start with the browser parsing URL.
  4. In the browser URL resolution, we incidentally understand the DNS domain name resolution, TCP three-way handshake and four-way wave of the two knowledge points.
  5. Finally, we know how browsers render pages.

To sum up, if we are just a point to focus on in the interview, we are likely to be asked dumb because we don’t know the beginning and end of the interview.

However, if we know a knowledge point, and the train of thought divergent, in-depth study, I believe that when the interviewer asked, partners can talk, and will not be asked to the whole body!