JS function stabilization and function throttling

Source: Internet
Author: User

We all know that frequent triggering of the execution of a certain JS logic code will have a great impact on performance, especially in the implementation of some effects, or the logic needs to make back-end requests, it will lead to lag, effect invalidation and other results, so in dealing with similar situations, you can consider using function throttling and function to shake to solve, As for the specific use of the method, according to the actual situation analysis, first to explain the concept of the two

Function throttling: In the case of frequent triggering, the logic that needs to be executed can only be executed after the next

function stabilization: In the case of frequent triggering, there is only enough idle time to execute the code once, and if it is not finished, it is removed and the logic is re-executed.

Application scenario: high-frequency triggering of the following methods

    • Page scrolling monitoring (onscroll)
    • Window resize events until the end of the window changes to run the business logic
    • Mouse Keyboard Mousedown/keydown Events
    • Mouse entry Move out event (Mouseenter/mouseleave)
    • Drag-and-drop functionality for DOM elements (MouseMove)
    • Input box search, etc. (KeyUp)

There is a big difference between the two concepts of function throttling and function stabilization, and we use a code example to see what

Example of a function throttle var can = True;window.onscroll = function () {  if (!can) {   ///To determine if the last logical execution is complete, and if in execution, return directly   ;  }  can = false;  SetTimeout (function () {    //execute logic    can = true;  }, 100);};

It can be seen that the last logic must be completed before the next logic will be executed, if we do not do the function of throttling, because scrolling is a frequent operation, will be constantly listening to, perform multiple logic trigger, do the throttling will be to a certain extent control logic trigger

function anti-shake var timer = Null;window.onscroll = function () {    if (timer) {      //clears the non-executed logic, re-executes the next logic, regardless of whether the last execution was completed      Cleartimeout (timer);     }    Timer = setTimeout (function () {        //execute Logic    }, 300);};

In the example of function stabilization, it can be seen that when an event is triggered by a monitor, regardless of whether the last logic has been executed, it should be removed and re-executed, and the function stabilization will reduce the frequency of the event being triggered.

Real use case explanation: On a list page, when the mouse enters the list of an item to display a tip prompt (the content of the message needs to be obtained by the request interface), move out to hide the prompt box. (The prompt is the relevant content of the current list item)

Diagram: This whole list, when we put the mouse to revise the situation need to display the details of the correction, and sometimes we mouse over the time may be the logic of each of the trigger, but this is not what we want, we just want to leave the last mouse on which data to show which piece of data logic, So according to the analysis of the situation, our situation is applicable to the function to shake

Code:

<!--HTML section of the MVVM frame's dom writing--><td  ms-mouseenter= "ToggleItem (true,item)" Ms-mouseleave= "ToggleItem (False , item) ">    <span>{{item.info}}</span>    <div ms-class=" show:item.isVisible ">        <p >item What you need to display </p>     </div></td>var event = null,toggleitem:function (state,item) {    if ( State==true) {        if (event) {            cleartimeout (event);        }        Event =settimeout (function () {            //the request to execute item displays the content logic        },100);    }    item.isvisible = State;},

Write in the final summary

So the most important thing is to first clearly distinguish between the concept of the two, understand the implementation of the method, and then according to the specific needs to determine which method to use to optimize, both in the functional realization of the essential difference.

JS function stabilization and function throttling

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.