JS function throttling and anti-shake

Source: Internet
Author: User

When you look at JS Advanced programming, you learn that a concept-function throttling-is designed to prevent the browser from crashing when certain events are triggered at high frequencies. Recently learned another concept, anti-shake, feeling and function throttling very much like, but also read a lot of blog posts, is understood.

Difference:

Function throttling: Frequent calls to a method that trigger at least one time within a certain interval

Anti-Shake: A method is called frequently within a certain interval of time, responding only to the last operation.

Function Throttling Application Scenario

Unlimited scrolling

Users scroll down infinitely scrolling pages, need to check how far the scroll position is from the bottom, and if near the bottom, we can send AJAX requests to get more data inserted into the page.

_.debounce is not suitable at this time because it is triggered only when the user stops scrolling. And we need to get the content as long as the user scrolls to the bottom of the neighborhood.

/* Function Throttle */function throttle (FN, delta, context) {    var safe = true;    return function () {        var args = arguments;        if (safe) {            Fn.call (context, args);            safe = false;            SetTimeout (function () {                safe = true;            }, Delta);}}    ;}

Anti-shake: application scenarios, such as input validation: until the user is finished, verify the correctness of the input and display the error message

/* Shake */function debounce (FN, delay,context) {let    handle;    return function () {        //cancel before the delay call        cleartimeout (handle);        Handle = SetTimeout (() = {           Fn.call (context);        }, delay);}    }

Reference article recommended http://web.jobbole.com/85035/

https://css-tricks.com/debouncing-throttling-explained-examples/(Article English original source)

https://juejin.im/post/5a142de15188251c11404085

JS function throttling and anti-shake

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.