New knowledge storeFront end from entry to groundFor attention, star and suggestions, update from time to time ~

Recently, I suddenly feel uneasy. I have seen a lot of things, but they don’t belong to me after a while. The result of sorting is very gratified, found a lot of knowledge points that I think I know but really don’t know.

Hope everyone who looks at the document can gain knowledge, and then leave a thumbs-up

Tell me you’ve been there, seen it, and earned it!

The front road is long, and you share!

Directories (i.e. directories) :

List in the way of title + summary, detailed explanation click on the title to view

Code specification

How to write code elegantly that doesn’t get beat up

Write code, must have good programming habits. What if it’s really bad

  1. No Code

No code is the best way to write secure and reliable applications. Write nothing; deploy nowhere.

  1. Thank colleagues do not kill the grace, usually cast more feed some snacks.

html

Talk about HTML semantics

Semantic elements clearly describe their meaning to browsers and developers. That is, the element itself conveys some information about the type of content the tag contains.

Why semantic?

  1. Page structure: Provides good content structure without CSS
  2. Good for SEO: crawlers rely on tags to determine the weight of keywords, so it can help crawlers grab more effective information
  3. Improve user experience: For example, title and Alt can be used to explain names or image information, and label can be flexibly used.
  4. Ease of team development and maintenance: Semantization makes your code more readable, makes your HTML structure more understandable to other developers, and reduces differentiation.
  5. Facilitate parsing by other devices: screen readers, blind readers, mobile devices, etc., to render web pages in a meaningful way.

Js based

Steal map town building ~ hand – in – hand take you into the JS in-depth road

A,Chaohuaxishi, reintroduce javascript types

An integral part of any programming language — type. JavaScript is a weakly typed or dynamic language. This means that you don’t have to declare the type of the variable in advance; the type will be determined automatically as the program runs.

Question: what is the result of 0.1 + 0.2 === 0.3? What about 0.1 + 0.3 === 0.4?

Second,Double grade (==) tips that beginners can’t miss

== equals the same, === equals strictly the same,

  • When comparing two operands: check the data types of the two operands. If they are the same, compare them. If they are different, cast them to the same type and then compare them.

  • JavaScript converts variables to Booleans according to the following rules:

    False, 0, empty strings (“”), NaN, null, and undefined are converted to false

All other values are converted to true

The above two paragraphs should be known, when asked can also answer up. However,

Question: what is the result of 1 === true? What about 2 === true?

Three,Clone: Do you really know the depth?

How to solve the circular reference problem?

Data is divided into basic data types (String, Number, Boolean, Null, Undefined, Symbol) and object data types.

1. Characteristics of basic data types: data stored directly in the stack

2, the characteristics of reference data type: store the object in the stack reference, the real data stored in the heap memory

En… These two statements are technically false

This description is not rigorous, so the following description is added:

  1. Basic data types: Variables correspond to a value
  2. Reference data type: the variable corresponds to an address that refers to an object in heap memory,

Note that the base data types are not always on the stack, only directly declared variables are.

Basic types are also placed on the heap if they are global. Primitive types, which are within reference types, are also placed on the heap.

Four,Chaohuaxishi, reintroduce inheritance and prototype chain

Only object types have the concepts of inheritance and archetypes, and the archetypes that are traced up together make up the prototype chain

Five,This refers to the arrow function

The function’s this keyword behaves slightly differently in JavaScript than in other languages. This refers to the environment object in which the code is currently executing. The value of this is determined by how the function is called.

Vi.Differences and simplified implementations of Apply, Call, and bind

  • apply()Method receives a specifiedthisValue and aAn array containing multiple parametersTo call a function.
  • call()Method receives a specifiedthisValue and aThe list of parametersTo call a function.
  • bind()Method to create a new function inbind()When called, of this new functionthisIs specified asbind()The remaining arguments will be used as arguments to the new function when called

Note when using call and apply that if the value passed to this is not an object…

Seven,Enlightening lexical scope and scope chain explanation

Scope is the area of a program’s source code where variables are defined. A scope specifies how to find a variable, that is, determine what access the currently executing code has to the variable.

JavaScript uses lexical scoping, also known as static scoping. Once the code is written, the scope is defined without execution, and this is known as lexical scope.

Eight,A brief introduction to the execution context and execution stack

An execution context is an abstraction of the context in which JavaScript code is evaluated and executed. Javascript code runs in an execution context.

The execution stack, which is a stack with LIFO (LIFO) data structures, is used to store all execution contexts created while the code is running.

There are only three types of JavaScript executable code: global code, function code, and Eval code. Accordingly, there are three types of execution context in JavaScript.

Nine,You may not know about variable promotion

In fact, let/const also has a variable boost.

Ten,In a few words with you to understand the “closure” | usage scenarios

  • Closures are internal functions, and we can do this by either inside a function or{}Block defines a function to create the closure. Closures can access an external scope even if the external scope is finished executing.
  • Closures are destroyed at the end of execution without being used externally
  • The outer scope of a closure is determined when it is defined, not when it is executed.

Eleven,Simple and clear “event loop /event loop” details

Javascript is a single-threaded language. Web-worker was proposed in the latest HTML5, but the core that javascript is single-threaded remains unchanged. No matter who writes the code, it has to be executed sentence by sentence.

Event loops can be understood as a way to achieve asyncrony, coordinating user interaction, scripting, rendering, networking, and other tasks.

Twelve,Lazy people finishing JS functional programming explained

  • Functional programming is a programming paradigm that treats computer operations as mathematically functional and avoids the use of program states and mutable objects.
  • Functional programming emphasizes the results of program execution rather than the process of execution. It advocates gradual calculation of results by using several simple execution units, and deduces complex operations layer by layer rather than designing a complex execution process.
  • The thinking process of functional programming is completely different. It focuses on functions, not procedures. It emphasizes how to solve problems by combining and transforming functions, rather than what kind of statements can I write to solve problems

On the front end, we see a lot of functional programming: In ES6, arrow functions were added, Redux introduced Elm to reduce the complexity of Flux, React16.6 introduced react.Memo () to make pure functional Components possible, and 16.8 introduced Hook. It is recommended to write components using pure Function…

Thirteen,Can not use but you must understand the details of Web workers

Web workers are concepts introduced in HTML5 that allow you to load and run one or more separate JavaScript threads within the main thread of a page.

The multithreaded programming capability provided by Web workers is different from traditional multithreaded programming (Java, C++, etc.). There is no scope or resource shared between the main program thread and Worker thread or between Worker threads. The only communication between them is an event-based listening message.

Fourteen,Met a Blob 🙈 🙈 🙈

What is a Blob

Blob (Binary Large Object) represents a Large Object of Binary type. In a database management system, the storage of binary data as a single collection of individuals.

A Blob object represents an immutable, raw data-like file object. Blobs don’t necessarily represent data in JavaScript’s native format. The File interface is based on Blob, inheriting the functionality of Blob and extending it to support files on the user’s system.

Generate a Blob

To construct a BLOb from other non-BLOb objects and data, use the blob () constructor.

The Blob() constructor returns a new Blob object. The content of a BLOB consists of a concatenation of values given in an array of parameters.

Grammar:

var aBlob = new Blob( array, options );
Copy the code

Blob usage scenarios

  1. Shard to upload

File objects are special types of BLOBs that can be used in the context of any Blob type.

For large file transfer scenarios, we can use the Slice method to slice large files and then slice them for uploading.

  1. Storing downloaded data

Data downloaded from the Internet can be stored in Blob objects. For example, in some image interfaces that require authentication, we can use fetch, attach authentication information to the request, download the BLOB object, and then use the bloB as a URL using the following method. Or build Blob objects directly on the front end to download front-end files.

  1. Blob as a URL

Blob can be done easily,Or the URL of another tag. Blob URL/Object URL is a pseudo-protocol that allows Blob and File objects to be used as URL sources for images, links to download binary data, etc.

In the browser, we create the Blob URL using the url.createObjecturl method, which takes a Blob object and creates a unique URL for it. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object. This method creates the memory reference address of an incoming object

The Blob and ArrayBuffer

  • Both BLOBs and ArrayBuffers can store binary data. Blobs store relatively large binary data (such as File File objects).
  • An ArrayBuffer object represents a primitive binary data buffer, that is, a binary buffer (container) of a specified size allocated in memory that is used to store the data of various typed arrays. It is the most basic primitive data container and cannot be read or written directly. Instead, it needs to be read or written through a specific view. That is, a TypedArray object or DataView object reads or writes memory size; A Blob object represents an immutable, raw data-like file object.
  • An ArrayBuffer is stored in memory and can be manipulated directly. Blobs can be on disk, cache memory, and other locations that are not available.

I still need the server worker and promise. I can arrange it when I have energy

css

A,CSS Position attribute and sticky attribute value

The CSS Position property is used to specify how an element is positioned in a document. The top, right, bottom, and left attributes determine the final position of the element. There are six values, including static, relative, fixed, absolute, sticky, and inherit.

Sticky sticky positioning can be considered as a mixture of relative and fixed positioning. The element is described as relative when it is in the display area of the screen or scrolling element, and fixed when it is rolled out of the display.

Second,Reflow and Repaint, KFC and MC

Backflow and redraw will affect page performance, and these two will be mentioned at the same time every time. The relationship is almost as close as the MC beside KFC.

  • Backflow occurs when the browser rerenders part or all of the document when the size, structure, or attributes of some or all of the elements in the Render Tree change.

  • When a change in the style of an element in a page does not affect its position in the document flow (e.g., color, background-color, visibility, etc.), the browser assigns the new style to the element and redraws it, a process called redraw.

Three,Viewport and 1 px | tools: this is a 1 px, designer: no, it isn’t

Designer: Your font size is not quite right Toolman: Look at the code, it’s 16px Designer: It’s really not the same as the design (pulls out the iPhone 11 Max) Toolman: I usually call this a rich man’s annoyance (pulls out the 5-inch Android) Designer: Ok

DPR(devicePixelRatio) devicePixelRatio, which is the ratio of device pixels to CSS pixels when the default zoom is 100%. In simple terms, this tells the browser how many actual pixels of the screen should be used to draw a single CSS pixel.

Four,Edible “dry” CSS layout, pure Html example, can debug | horizontal, vertical, multiple columns

This article only collates the commonly used horizontal center, vertical center and multi-column layout, not all involved, only consider commonly used and can be used conveniently. If there are other clever solutions, please point them out in the comments and I will add them to the document in time.

All of the examples in this article are HTML rendered, so you can simply select them and debug them on the console. I recommend you try the tips listed in this article to help you understand.

Five,Front end must master “CSS cascade context” explain | hand knock example, BaoJiao package

Most people, after learning CSS initially, have the impression that z-index is used to define the stack order of an element on the z-axis of the screen. But the z-index attribute only works on position elements (elements that define the position attribute and have a non-static value).

Stacking context is a three-dimensional concept in HTML. It demarcates some kind of domain or scope, separates the inside from the outside at the level of rendering rules, and gives some characteristics to the elements themselves and their inner regions.

Elements that have a cascading context become cascading context elements due to specific CSS Settings;

The cascading context element has the following properties:

  1. Cascading contexts are layered at a higher level than normal elements;
  2. The cascading context can be nested, and the inner cascading context and all its children are subject to the outer cascading context.
  3. Each cascade context is self-contained, and when an element is cascaded, the entire element is considered to be in the cascade order of the parent context.
  4. Each cascading context is independent of its sibling, meaning that only descendant elements need to be considered when cascading or rendering.
  5. The cascading context blocks the element’s blending mode;

Vi.Sass. Vs. Less | introduction and comparison

“Which CSS preprocessor language should I choose?”

  • Less (short for Leaner Style Sheets) is a backward-compatible CSS extension language. Because Less is so much like CSS, it only adds a few handy extensions to the CSS language, making it easy to learn.
  • Sass, as “the most mature, stable and powerful professional CSS extension language in the world”. Compatible with all versions of CSS, and there are countless frameworks built using SASS.

Seven,Refused to gray | in addition to solve the overlapping margins, landing the also can use it

Margin overlap

Margin overlap is margin-collapse. The margins of two adjacent boxes (which may be siblings or ancestors) can be combined to form a single margin. This merging of margins is called folding, and the combined margins are called folded margins.

The folding results follow the following calculation principles:

  • When two adjacent outer margins are positive, the result of folding is the greater of them;
  • When two adjacent margins are both negative, the result of folding is the greater value of their absolute values;
  • When two margins are positive and negative, the result of folding is the sum of them;

What is BFC?

Block formatting context (BFC). It is a separate rendering area, with only block-level box participation, which dictates how the internal block-level box is laid out and has nothing to do with the outside of the area.

We often say that the document flow is actually divided into location flow, floating flow, common flow three kinds. Normal flow is the FC of BFC. FC(Formatting Context) is a rendering area on a page that has a set of rendering rules that determine how its sub-elements are positioned and how they relate to and function with other elements.

BFC trigger mode

  1. The root element, the HTML tag
  2. Float elements: Float values are left and right
  3. The overflow value is not visible, but auto, Scroll, and hidden
  4. The display value is inline-block, table-cell, table-caption, table, inline-table, flex, inline-flex, grid, inline-grid
  5. Positioning elements: Position values are Absolute and fixedNote: display: tableThe BFC can also be generated because the Table generates an anonymous table-cell by default. This anonymous table-cell generates the BFC.

Landing the role of

The BFC is a separate container on the page, and the child elements inside the container do not affect the outside elements and vice versa. We can do a lot with this feature of the BFC.

  1. Margins fold under the same BFC
  2. BFC can contain floating elements (clear floating)
  3. The BFC prevents elements from being overwritten by floating elements

Eight,Silly points not clear CSS | percentage (negative) benchmark is the length of the who

  1. Width height percentage

    When the height and width of an element are set to percentages, they are based on the height and width of the block-level object containing them, respectively. That’s what regular percentages mean.

  2. Margin Percentage The percentage value of the margin is calculated according to the width of the block it contains. When the writing mode becomes vertical, the reference will be changed to the height of the containing block. why

The definitive guide to CSS:

We believe that the normal flow of most elements will be high enough to contain the descendant elements (including from the outside), if an element of the up and down the outside is the height of the parent element percentage, can lead to an infinite loop, the parent element height increases, the increase of elements from the outside to adapt to the posterity, and accordingly, The upper and lower margins increase as the parent element height increases.

  1. The padding percentage is the same

  2. In standard box model, width: 100%; padding: 10% 10%; Box-sizing: border-box; width (); width (); width (); width (); width (); width (); width (); width (); width (); width ();

  3. Percentages are used in the Translate function based on the width and height of the element itself.

  4. Margin for the negative

    1. Negative margin – left margin – right
      • The element itself has no width and will increase its width
      • The element itself has a width, which causes displacement
    2. Margin-top is negative, regardless of whether the height is set, it will not increase the height, but will produce upward displacement
    3. When margin-bottom is negative, it does not shift and instead reduces its CSS reading height.
  5. Padding unfortunately, padding is not allowed to be negative and is invalid if it is

Specific interpretation and manual sample please click silly points not clear CSS | percentage (negative) benchmark is the length of the who

Nine,Carefully organize 33 CSS knowledge dry goods

I attached links to articles worthy of expansion at the end of the questions, which will have detailed explanation and case analysis. If you want to talk about the technology with the interviewer, you can have an in-depth look at this article.

  • What is the difference between the standard CSS box model and the lower version IE box model?
  • How is the CSS priority algorithm calculated?
  • How do I center div?
  • What are the values of display? What is their role?
  • The origin and characteristics of different values of position?
  • How to create a triangle with pure CSS
  • How does float work and when does it need to be cleared? How to clear the float?
  • What is the CSS preprocessor/post-processor? Why use them?
  • What’s the difference between a double colon and a single colon in ::before and :after?
  • The difference between pseudo-elements and pseudo-classes
  • What does the CSS property Content do?
  • What’s the difference between PX, EM and REM?
  • A height adaptive div that has two divs, one 100px high, and wants the other to fill the remaining height.
  • Transition, Transform and animation
  • What is line-height?
  • CSS margin overlap and prevention methods
  • What is BFC? How do I trigger the BFC? What’s the use?
  • display: none; With the visibility: hidden; What’s the difference?
  • What are the ways to hide elements?
  • What is the cause of the invisible space between Li and Li? What’s the solution?
  • How does JS get the position and width of the box model
  • How does the browser determine if an element matches a CSS selector
  • How to implement 1px on mobile
  • What properties of CSS can be inherited?
  • React Native CSS styles?
  • What is the difference between writing the style tag after the body and before it
  • position:fixed; How to deal with invalid under the mobile terminal?
  • What is reflux (rearrangement) and redraw and the difference
  • What are the specific differences between inline elements and block-level elements? Are the padding and margin of the inline elements settable?
  • What is the cause of img image margins? How to solve it?
  • Talk about CSS cascading contexts
  • CSS percentage unit relative to baseline

engineering

A,Take you rolled a belongs to own the react project | webpack + Babel + + eslint typescript

I have been writing the front end for more than a year, but I have not built a project from scratch. Now I start to step on the pit.

The project generally includes the following parts

  • Directory specification
  • react
  • webpack
  • less
  • typescript
  • eslint

Hand in hand teaching, you can finish

  • An introduction towebpackTo understandbabel
  • Learn to configuretypescript + eslint
  • I built a React project myself

network

JSON Web Token(JWT

JSON Web Token (JWT) is currently the most popular cross-domain authentication solution,

The token is designed to be compact and secure, especially suitable for single sign-on (SSO) scenarios in distributed sites. The JWT declaration is generally used to pass authenticated user identity information between the identity provider and the service provider to obtain resources from the resource server, and to add some additional declaration information necessary for other business logic. The token can also be used directly for authentication or can be encrypted.

Traditional session authentication

The HTTP protocol itself is stateless, which means that if a user provides a user name and password to our application for user authentication, the user has to authenticate again on the next request.

The general request flow is as follows.

  1. The user sends the user name and password to the server.
  2. After the authentication, the server saves relevant data in the current session, such as user role, login time, and so on.
  3. The server returns a session_ID to the user and writes the user’s Cookie.
  4. The session_id is passed back to the server via cookies with each subsequent request from the user.
  5. The server receives the session_id, finds the previously saved data, and learns the user’s identity.

Problems with session authentication

  • Server overhead: After each user is authenticated by the application, the application records each user on the server to facilitate the identification of the user’s next request. Generally, sessions are stored in memory. As the number of authenticated users increases, the overhead of the server increases significantly.
  • Scalability: If the authentication record is kept in memory, this means that the next request from the user must be made on the same server in order to obtain the authorized resources, which limits the load balancer’s ability in distributed applications. This also means limiting the application’s ability to scale.
  • Another option is to persist session data to a database or other persistence layer. Upon receiving the request, the various services request data from the persistence layer. The advantage of this scheme is the clear structure, but the disadvantage is the large amount of engineering. In addition, if the persistence layer fails, it will fail in a single point.
  • CSRF: Because user identification is based on cookies, if cookies are intercepted, users will be vulnerable to cross-site request forgery.

Token-based authentication mechanism

The token-based authentication mechanism is stateless like HTTP, but it does not need to retain user authentication information or session information on the server.

The process looks like this:

  1. The user requests the server using a username and password
  2. The server validates the user’s information
  3. The server passes authentication and returns a token to the user

4. The client stores the token and sends the token value with each request. The server validates the token value and returns data

The server must support the CORS(Cross-source resource sharing) policy. Generally, set access-Control-allow-Origin: * on the server.

Several characteristics of JWT

  1. JWT is not encrypted by default. Once the original Token is generated, it can be encrypted again with the key.

  2. Secret data cannot be written to the JWT without encryption.

  3. JWT can be used not only for authentication, but also for information exchange. Using JWT effectively can reduce the number of times the server queries the database.

  4. Since the server does not store session state, it is not possible to revoke a token or change the permission of the token during use. That is, once a JWT is issued, it remains valid until expiration, unless the server deploys additional logic.

  5. The JWT itself contains authentication information, and if it is disclosed, anyone can gain full access to the token. To reduce theft, JWT expiration dates should be shorter. For some important permissions, the user should be authenticated again.

  6. To reduce theft, JWT should use HTTPS instead of HTTP.

Meet cross-domain 🙈🙈🙈

Whether you’ve encountered it or not, I’m sure you’ve heard of cross-domains. In actual projects, there are many cross-domain problems. The following describes several common methods for cross-domain communication between documents and cross-domain communication between the front and back.

What is cross-domain

Simply put, cross-domain occurs when documents or scripts executed in one domain want to access resources in another domain or communicate with another domain. For example,, load resource files or pages in other domains through link in, Ajax request to background domain name initiated by JS, or communication between parent page and sub-level IFrame of different domains, etc.

To understand cross-domains, you must first understand what a domain is.

What is a domain

Unlike a domain name, a cross-domain domain is a concept defined by the browser’s same-origin policy.

The Same Origin Policy (SOP) is a convention introduced by Netscape into the browser in 1995. It is the core and most basic security function of the browser. Without the Same Origin policy, the browser is vulnerable to XSS and CSFR attacks.

Same-origin indicates that the protocol, domain name, and port of a resource or destination address are the same. Even if different domain names point to the same IP address, they may also be from different sources.

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain

Nonhomologous restriction

  1. Cookies, LocalStorage, and IndexedDB of non-cognate web pages cannot be read
  2. DOM of non-homologous web pages cannot be accessed
  3. Unable to send AJAX requests to non-same-origin addresses

How to solve cross-domain problems

For communication between documentsCopy the code
  1. Set document.domain to resolve cookies that cannot read non-cognate web pages

Because the browser checks whether two pages are identical through the document.domain property, two pages can share cookies by setting the same Document.domain (this scheme is only applicable to cross-domain scenarios where the primary domain is the same and the subdomain is different).

// Set document.domain = 'test.com';Copy the code

Ps: Cookies are basically planted under the master domain name to ensure that pages with the same domain name can share token and other information. At the same time, cookies under the current domain name will be automatically attached to new same-domain pages

  1. Cross-document communication API: window.postmessage ()

This approach can safely implement cross-source communication and is secure as long as it is used correctly.

It can be used to solve the following problems:

  • Data transfer between the page and the new window it opens
  • Messaging between multiple Windows
  • Page with nested IFrame message delivery
  • Cross-domain data transfer for the three scenarios above

A window can get a reference to another window (such as targetWindow = window.opener) and then distribute a MessageEvent message by calling the targetwindow.postMessage () method on the window. The window receiving the message is free to process this event as needed. grammar

otherWindow.postMessage(message, targetOrigin, [transfer]);
Copy the code
  1. The json cross-domain

The SRC attribute of the

<script SRC ="http://test.com/data.php?callback=dosomething"></script> // make a request to the server test.com. The query string of the request has a callback argument, <script type="text/javascript"> function dosomething(res){// Process the data obtained console.log(res.data) } </script>Copy the code
  1. CORS cross-domain

CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and a fundamental solution for cross-source AJAX requests. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.

The entire CORS communication process is completed automatically by the browser without user participation. As soon as the browser discovers that an AJAX request crosses sources, it automatically adds some additional headers, and sometimes an additional request, but the user is unaware of it.

1. For common cross-domain requests, you only need to set access-Control-allow-origin on the server. Cross-domain request with cookie: Both the front and back ends need to be setCopy the code

Browsers divide CORS requests into two types: Simple request and not-so-Simple Request. Browsers handle these two types of requests differently.

  1. The WebSocket protocol is cross-domain

WebSocket Protocol is a new protocol for HTML5. It implements full duplex communication between browser and server, and allows cross-domain communication. It is a good implementation of server push technology.

The native WebSocket API is inconvenient to use. Socket. IO is recommended. It encapsulates the WebSocket interface, provides a simpler and more flexible interface, and provides backward compatibility for browsers that do not support WebSocket.

  1. Nginx agents cross domains

The same origin policy is a security policy of the browser and is not part of the HTTP protocol. The server invokes the HTTP interface only using THE HTTP protocol, and does not execute JS scripts. There is no need for the same origin policy, so there is no crossing problem.

Through nginx configuration of a proxy server (domain name and website domain name is the same, different port) as a jumper, reverse proxy access background interface, and can incidentally modify the cookie in the domain information, convenient cookie writing in the current domain, to achieve cross-domain login.

  1. Node agents cross domains

In essence, it starts a proxy server to forward data. It can also modify the domain name in the cookie in the response header by setting the cookieDomainRewrite parameter to write cookies to the current domain and facilitate interface login authentication. Express + HTTP-proxy-middleware is used to build a proxy server, which is used in Webpack-dev-server.

react

A,React hook

Debounce and throttle are common front-end utility functions. Function image stabilization

When an event is continuously triggered and no event is triggered again within a certain period of time, the event handler will execute once. If the event is triggered again before the specified time, the delay will start again.

function debounce(fn, ms) { let timer; return function(... args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn(... args) timer = null; }, ms); }}Copy the code

It is important to remember that the stabilization function should be called only once.

Function of the throttle

Ensure that an event handler is called only once in a certain period of time when an event is continuously raised.

function throttle(fn, ms) { let timer; return function(... args) { if (timer) return; canRun = false; timer = setTimeout(() => { fn(... args); timer = null; }, ms); }}Copy the code

It is important to remember that the stabilization function should be called only once.

Hook up being

function useDebounce(fn, delay, dep = []) { const { current } = useRef({ fn, timer: null }); useEffect(function () { current.fn = fn; }, [fn]); return useCallback(function f(... args) { if (current.timer) { clearTimeout(current.timer); } current.timer = setTimeout(() => { current.fn.call(this, ... args); }, delay); }, dep) }Copy the code

Hook the throttle

function useThrottle(fn, delay, dep = []) { const { current } = useRef({ fn, timer: null }); useEffect(function () { current.fn = fn; }, [fn]); return useCallback(function f(... args) { if (! current.timer) { current.timer = setTimeout(() => { delete current.timer; }, delay); current.fn.call(this, ... args); } }, dep); }Copy the code

Please click on the title for the specific principle and analysis of the use of anti-shake and throttling in hook

To be continued

For collection attention, by the way in the left sidebar of the first button hard click on the better. This is the biggest recognition for me.

Limited ability, if you have good knowledge or different opinions, welcome to comment below, I will timely follow up.