Update: Thank you for your support, recently toss a summary of information, convenient for you to read the system, there will be more content and more optimization, click here to view
—— The following is the text ——
The introduction
The second issue of the semi-monthly is coming. During this time, 10 frequently used Interview questions have been added to the Daily- interview-question. Today, I will send you the Interview questions and some answers summarized in the last half month to help you check and fill in the gaps.
Please leave your answers in the project Issue area. If you have any questions, please feel free to discuss them.
The project address is: Daily- interview-question
A brief explanation of HTTP2 multiplexing
In HTTP/1, each request will establish a TCP connection, which is often referred to as three handshakes and four waves. This takes a long time in the process of a request. Even if keep-alive is enabled and the problem of multiple connections is solved, there are still two efficiency problems:
- The first one: serial file transfer. When file A is requested, file B can only wait until a connects to the server, the server processes the file, and the server returns the file. Let’s assume that all three steps take 1 second, so file A takes 3 seconds, file B completes transfer in 6 seconds, and so on. (Note: there is a prerequisite for this calculation, that is, the browser and the server are single-channel transmission.)
- Second: too many connections. Let’s assume that Apache sets the maximum number of concurrent requests to 300. Because of browser limitations, the maximum number of requests that the browser can make is 6 (Chrome), which means that the server can handle 50 concurrent requests. When the 51st person visits, the server will have to wait for one of the previous requests to complete.
HTTP2 is delivered in binary format, replacing the text format of Http1. x, which is parsed more efficiently. Multiplexing replaces the sequence and blocking mechanism of HTTP1.x, where all requests for the same domain name are completed concurrently over the same TCP connection. In HTTP1.x, multiple concurrent requests require multiple TCP connections, and browsers limit the number of TCP connections to 6-8 for resource control. In the HTTP2
- All communication under the same domain name is completed on a single connection, eliminating the delay and memory consumption caused by multiple TCP connections.
- Requests and responses can be interleaved in parallel on a single connection, with no interference between them
github.com/Advanced-Fr…
Question 16: Talk about your understanding of TCP three-way handshake and four-way wave
github.com/Advanced-Fr…
Question 17: A, B after normal connection, B machine suddenly restart, ask A at this time in the TCP state
If A and B have established A normal connection but never sent data to each other, then B suddenly restarts. What is the TCP status of A? How do I eliminate this state in the server program? (Beyond the topic, understanding can be)
Because B will enter the LISTEN state of the TCP state machine after the restart, as long as A sends another packet (whether SYN packet or application data), B will actively send a reset packet with RST bit to reset the connection, so A should be in the SYN_sent state.
github.com/Advanced-Fr…
When is setState synchronized or asynchronous in React?
In React, if an event handler is raised by React (such as an event handler raised by onClick), calls to setState do not update this.state synchronously. “In addition” refers to the event handlers added directly via addEventListener, bypassreact, and the asynchronous calls made via setTimeout/setInterval.
* * reason: ** When implementing the React setState function, we use the variable isBatchingUpdates to determine whether to update this.state directly or put it in a queue later. IsBatchingUpdates are false by default. SetState updates this.state. However, there is a function called batchedUpdates that changes isBatchingUpdates to t rue. When React calls batchedUpdates before the event handler is called, the result is that setState controlled by React does not update this.state synchronously.
github.com/Advanced-Fr…
19. React setState: What does the following code say?
class Example extends React.Component {
constructor() {
super(a);this.state = {
val: 0
};
}
componentDidMount() {
this.setState({val: this.state.val + 1});
console.log(this.state.val); // 第 1 次 log
this.setState({val: this.state.val + 1});
console.log(this.state.val); // log the second time
setTimeout(() = > {
this.setState({val: this.state.val + 1});
console.log(this.state.val); // log the third time
this.setState({val: this.state.val + 1});
console.log(this.state.val); // log the fourth time
}, 0);
}
render() {
return null; }};Copy the code
Resolution:
1. Both the first and second updates are in the react lifecycle. IsBatchingUpdates are true when triggered, so the update state is not directly implemented.
When setState is set twice, this.state.val is 0, so 0 is set to 1. React will merge the setState and execute it only once. The value of state.val is set to 1.
3, setTimeout code, isBatchingUpdates is false, so it can directly update, so it is connected to output 2,3.
Output: 0, 0, 2, 3
github.com/Advanced-Fr…
Q20: Introduce the NPM module installation mechanism. Why can I automatically install the corresponding module by typing NPM install?
Resolution:
1. Installation mechanism of NPM module:
- a
npm install
The command - Query whether the specified module already exists in the node_modules directory
- If yes, do not reinstall it
- If there is no
- NPM queries Registry for the url of the module zip package
- Download the compressed package, stored in the root directory
.npm
In the directory - Unzip the zip package to the current project
node_modules
directory
2. Implementation principle of NPM
After entering the NPM install command and pressing Enter, the following phases (NPM 5.5.1 as an example) occur:
- Execute the project’s own preinstall
The current NPM project will be executed if the preinstall hook is defined.
- Identify the layer 1 dependency module
The first thing you need to do is identify the first-level dependencies in the project, which are the modules specified directly in the Dependencies and devDependencies properties (assuming that the NPM install parameter is not added at this point).
The project itself is the root node of the whole dependency tree, and each first-level dependency module is a sub-tree below the root node. NPM will start multiple processes from each first-level dependency module to gradually find nodes at deeper levels.
- Acquisition module
Acquiring a module is a recursive process divided into the following steps:
- Get module information. Before downloading a module, you first need to determine its version, because package.json is often a Semantic version (semver). If nPM-shrinkwrap. Json or package-lock.json has the module information in the version description file (nPM-shrinkwrap. If the version of a package in packaeg.json is ^1.1.0, NPM will go to the repository to get the latest version in the form of 1.x.x.
- Gets the module entity. The resolved field for the module will be obtained in the previous step. NPM will use this address to check the local cache and grab it if it is in the cache or download it from the repository if it is not.
- Look for the module dependency, go back to Step 1 if there are dependencies, and stop if there are none.
- Module flattening (DEDUPE)
The previous step obtained a complete dependency tree, which may contain a large number of duplicate modules. For example, module A depends on LoDash, and module B also depends on LoDash. Prior to NPM3, the installation was strictly based on the dependency tree structure, resulting in module redundancy.
Starting with NPM3, a dedupe process is added by default. It iterates through all nodes, placing modules one by one below the root node, the first layer of Node-modules. When duplicate modules are found, they are discarded.
Here we need a definition for duplicate modules, which means the modules have the same name and are semver-compatible. Each Semver has a set of versio-permitted ranges. If the versio-permitted ranges of two modules overlap, a compatible version can be obtained without having to have the same version number. This allows more redundant modules to be removed during dedupe.
- Install the module
This step will update node_modules in the project and execute the lifecycle functions in the module (in preinstall, install, postinstall order).
- Execute the project’s own life cycle
The current NPM project will be executed if hooks are defined (install, postinstall, prepublish, prepare).
The last step is to generate or update the version description file, and the NPM install process is complete.
github.com/Advanced-Fr…
Question 21: there are three ways to judge arrays, please introduce the differences and advantages and disadvantages of them respectively
Object. The prototype. ToString. Call (), instanceof and Array. The isArray ()
Resolution:
1. Object.prototype.toString.call()
Every Object that inherits Object has a toString method, which, if not overridden, returns [Object type], where type is the type of the Object. However, when toString is used directly on objects other than Object, it returns a string of contents, so we need to use call or apply to change the execution context of toString.
const an = ['Hello'.'An'];
an.toString(); // "Hello,An"
Object.prototype.toString.call(an); // "[object Array]"
Copy the code
This method evaluates all basic data types, even null and undefined.
Object.prototype.toString.call('An') // "[object String]"
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call({name: 'An'}) // "[object Object]"
Copy the code
Object. The prototype. ToString. Call () is often used to judge the built-in browser Object.
2. instanceof
Instanceof’s internal mechanism is to determine whether the prototype of the type can be found in the prototype chain of the object.
Use instanceof to determine whether an object is an Array. Instanceof checks whether the object’s archetype is found in the Array’s archetype chain, returning true if it is found, false otherwise.
[] instanceof Array; // true
Copy the code
However, instanceof can only be used to determine object types, not primitive types. And all Object types instanceof Object are true.
[] instanceof Object; // true
Copy the code
3. Array.isArray()
-
Function: Used to determine whether an object is an array
-
Instanceof with isArray
Array.isArray is superior to instanceof when detecting Array instances because array. isArray can detect iframes
var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; var arr = new xArray(1.2.3); / / [1, 2, 3] // Correctly checking for Array Array.isArray(arr); // true Object.prototype.toString.call(arr); // true // Considered harmful, because doesn't work though iframes arr instanceof Array; // false Copy the code
-
Array. IsArray () and the Object. The prototype. ToString. Call ()
Array. IsArray () is the ES5 new method, when there is no Array. The isArray (), you can use the Object. The prototype. ToString. Call () implementation.
if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } Copy the code
github.com/Advanced-Fr…
22. Repaint & Reflow and how to optimize it
Resolution:
1. Browser rendering mechanism
- Browsers use a streaming layout model (
Flow Based Layout
) - The browser will put
HTML
Parsed intoDOM
,CSS
Parsed intoCSSOM
.DOM
andCSSOM
The merge results in a render tree (Render Tree
). - There are the
RenderTree
, we know the style of all the nodes, calculate their size and position on the page, and finally draw the nodes on the page. - Since browsers use streaming layouts, yes
Render Tree
Is usually done only once,Except for tables and their internal elements, which can be evaluated multiple times, usually three times as long, which is one of the reasons to avoid table layouts.
2. Redrawn
Redraw a node whose geometry or style changes without affecting the layout, such as outline, visibility, color, background-color, etc. Redraw is expensive because the browser must verify the visibility of other node elements in the DOM tree.
3. Return
Backflow is when layout or geometry properties need to be changed. Backflow is a key factor affecting browser performance because it involves updating the layout of part of the page (or the entire page). The backflow of an element can result in subsequent backflow of all its child elements, as well as subsequent nodes in the DOM and ancestor node elements.
<body> <div class="error"> <h4> My component </h4> <p><strong> Error: </strong> Error description... < / p > < h5 > error-correction < / h5 > < ol > < li > the first step < / li > < li > step 2 < / li > < / ol > < / div > < / body >Copy the code
In the HTML fragment above, backflow on the paragraph (
tag) would cause a strong backflow because it is a child node. This also results in ancestor backflow (div.error and body-depending on the browser). In addition,
and < OL > also have simple backflow, because these nodes come after backflow elements in the DOM. Most of the backflow will cause the page to be re-rendered.
Backflow must occur redraw, redraw does not necessarily cause backflow.
4. Browser optimization
Most modern browsers are batch update layout through the queue mechanism, the browser will put the modification operations in the queue, at least one browser refresh (16.6 ms) will empty the queue, but when you get the layout information, the queue may affect the properties or methods return value of the operation, if not, the browser will be forced to empty the queue, Trigger backflow and redraw to ensure the correct value is returned.
These include the following attributes or methods:
offsetTop
,offsetLeft
,offsetWidth
,offsetHeight
scrollTop
,scrollLeft
,scrollWidth
,scrollHeight
clientTop
,clientLeft
,clientWidth
,clientHeight
width
,height
getComputedStyle()
getBoundingClientRect()
Therefore, we should avoid frequent use of the above attributes, which force the render to refresh the queue.
5. Reduce redrawing and reflow
- CSS
- Use transform instead of top
- Use visibility instead of display: None, because the former will only cause redraw and the latter will cause backflow
- Avoid table layoutsIt can be a small change that causes the whole thing
table
Relayout. - If possible, change the class at the very end of the DOM tree. Backflow is inevitable, but its impact can be reduced. Changing the class as far down the DOM tree as possible limits the scope of backflow, affecting as few nodes as possible.
- Avoid multiple inline styles and CSS selectors match from right to left to avoid too many nodes.
<div>
<a> <span></span> </a>
</div>
<style>
span {
color: red;
}
div > a > span {
color: red;
}
</style>
Copy the code
For the first style, the browser just needs to find all the SPAN tags on the page and set the color, but for the second style, the browser needs to find all the SPAN tags, then find the A tag on the SPAN tag, and finally find the div tag. Then color span tags that match this condition, and the recursive process becomes complicated. So we should avoid writing too specific CSS selectors as much as possible, and add as few meaningless tags to THE HTML as possible to keep the hierarchy flat.
- Apply the animation to an element whose position attribute is absolute or fixedTo avoid affecting the layout of other elements, so that only a redraw rather than reflux, while controlling the animation speed can be selected
requestAnimationFrame
, as shown in theExplore requestAnimationFrame. - Avoid using CSS expressions, which may cause backflow.
- Set nodes that are frequently redrawn or refilled as layers, layers can prevent the rendering behavior of this node from affecting other nodes, for example
will-change
,video
,iframe
And the browser will automatically turn the node into a layer. - CSS3 Hardware acceleration (GPU acceleration), using CSS3 hardware acceleration, can make
transform
,opacity
,filters
These animations do not cause backflow redraw. But other properties of the animation, for examplebackground-color
This will still cause backflow redraw, but it will still improve the performance of these animations.
-
JavaScript
-
To avoid manipulating styles too often, it is best to override the style property once, or define the style list as class and change the class property once.
-
To avoid frequent DOM manipulation, create a documentFragment, apply all DOM manipulation to it, and finally add it to the document.
-
Avoid frequently reading properties that cause backflow/redraw, and if you do need to use them more than once, cache them in a variable.
-
Use absolute positioning on elements with complex animations to keep them out of the document stream, which would otherwise cause frequent backflow of parent elements and subsequent elements.
-
github.com/Advanced-Fr…
Question 23: What is the difference between the observer and subscription-publish modes
Resolution:
contact
The publish-subscribe pattern is a variation of the Observer pattern. Publish-subscribe simply abstracts part of the functionality into a separate ChangeManager.
intentions
Each object (Subject, publisher) changes, notifying observers (observers, Subscribers) that are dependent on it.
Differences and application scenarios
In general, the publish-subscribe model is suitable for more complex scenarios.
In a “one to many” scenario, a publisher notifies only some of its subscribers of an update?
In the many-to-one or many-to-many scenario. A subscriber depends on multiple publishers. Does one publisher need to notify subscribers of updates? Or wait until all publishers have updated before notifying subscribers?
All of this logic can be put into the ChangeManager.
github.com/Advanced-Fr…
24. Talk about the design ideas of Redux and Vuex
Feel free to leave your answers in the Issue section.