Function throttling for onScroll events triggered by JavaScript

Source: Internet
Author: User
The content of this article is to talk about the common problems encountered in my work recently. It is mainly about the Function throttling of the onScroll event triggered by JavaScript. This article starts with a common problem and introduces the solution step by step. If you need it, let's take a look at it with the small Editor. Problem description

The common website layout is A navigation bar on the top. Suppose there are four topics on this page: A, B, C, and D. Click A. The Anchor jumps to column, at the same time, the button on the top is highlighted. Click B, the anchor jumps to Column B, and the B button on the top is highlighted. We scroll in the Main component and when we scroll to Module B, the B button is highlighted. The above is a model we often encounter during development. If jQuery was used for front-end development in the past, it would be too familiar.

Solution

I would like to talk about the performance optimization methods in React componentized development.

The structure of our page is as follows:

{ this.main = main; }} onScroll={ ((/detail/.test(this.props.location.pathname))) ? (() => this.throttle()()) : null }> {this.props.children}

We set the onScroll event in the main component. In this event, we trigger the action and pass the state change to the child component through redux.

My scroll event trigger function is like this (ignore a long string of if else, this is the ultimate solution to solve the bug of one afternoon, this article will not be explained)

HandleScroll () {const {changeScrollFlag} = this. props. actions; // modify the style const {basicinformation, holderinformation, mainpeople, changerecord }={ basicinformation: document. getElementById ('basicinformation '). offsetTop-121, holderinformation: document. getElementById ('holderrorinformation '). offsetTop-121, mainpeople: document. getElementById ('mainpeople '). offsetTop-121, changerecord: document. getElementById ('changerecord '). offsetTop-121,}; if (window. screen. availHeight> this. main. scrollTop) {document. getElementById ('gototop '). style. display = 'none';} else {document. getElementById ('gototop '). style. display = 'block';} // obtain the offsetTop of the basic information area, shareholder information area, primary personnel area, and change record area, we use it to trigger action when comparing/comparing the result with the scrollTop of main, and change the TitleBox component style if (this. main. scrollTop 

The changeScrollFlag () function is our action processing function.

Our function throttling

Throttle () {// onScroll function throttle let previous = 0; // previous initial setting the last onScroll function call time point is 0. Let timeout; const wait = 250; // One return () =>{ const now = Date. now (); const remaining = wait-(now-previous); if (remaining <= 0) {if (timeout) {window. clearTimeout (timeout);} previous = now; timeout = null; this. handleScroll ();} else if (! Timeout) {timeout = window. setTimeout (this. handleScroll, wait );}};}

Our throttling function returns a function that sets a timestamp. If the difference between our timestamp is small, we do nothing, but the difference between our timestamp is large, clearing the timer, trigger the scroll function. This seems simple, right, and indeed simple.

What else do we need to do in child components?

Receive action

The second-level container component receives the action and transmits the props to the third-level display component through the second-level container component.

We must receive this props in componentWillReceiveProps.

Remember, using this. props in componentWillReceiveProps cannot receive props changes !!! The component lifecycle function contains a parameter of its own.

ComponentWillReceiveProps (nextProps) {// In compoWillReceiveProps, The system receives the index of the onScroll event triggered by the Main component to change the activebtn style and sets it to the state of this component. setState ({activebtn: nextProps. scrollFlag. scrollIndex ,});}

The highlighted button in our state control is a number.

Change the style of the navigation bar

 this.handleClick(1, 'basicinformation')}>

Here, we have completed a process of triggering events from the top-level components, implementing function throttling, and passing events to the underlying presentation components layer by layer.
Recent feelings about front-end development

Do not call a function repeatedly in the component, which will cause huge consumption! We can do things through the ternary operators and template strings. Do not write a new function.

Jsx should not be too redundant. We try to write variables as much as possible. Otherwise, the page structure is complicated and it is not easy for us to catch bugs.

Reduce the number of backend requests, save the cookie if the cookie is saved, and save the localStorge if the localStorge is saved.

Try to write simple components by yourself. Do not use other components. Otherwise, there will be great difficulties in demand change and style adjustment and some meaningless things will be done.

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.


For more information about function throttling that triggers the onScroll event using JavaScript, see the Chinese PHP website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.