Analysis of JS function throttling and function stabilization

Source: Internet
Author: User
Tags event listener

Question 1: If the DOM drag-and-drop function is implemented, but when the binding drag event found that every time the element moved a little bit to trigger a large number of callback functions, causing the browser to die directly, this time what to do?

Question 2: If a button is bound to the post event submitted by the form, but the user sometimes in the network situation is very poor, multiple clicks on the button caused the form to repeat the submission, how to prevent the occurrence of multiple submissions?

In order to deal with the above scenario, there are two concepts of function stabilization and function throttling , in general: The two methods are to control the execution times of functions on the timeline.

1. Function stabilization (debounce)

Concept: The callback is executed after the event has been triggered for n seconds, and is re-timed if it is triggered again within this n seconds.

Example of life: If someone enters the elevator (triggering event), then the elevator will start in 10 seconds (execute the event listener), then if another person enters the elevator (in 10 seconds to trigger the event again), we have to wait 10 seconds to start again (re-timer).

2. function throttling (throttle)

Concept: Specify a unit of time, in this unit time, only one trigger event callback function execution, if an event is triggered multiple times in the same unit time, only once can take effect.

Examples of life: we know that the present is that when 1 seconds of continuous playback of more than 24 pictures, in the eyes of the human eye will form a coherent animation, so in the movie is basically played at 24 per second speed, why not 100 or more? Because 24 of them can meet human visual needs, 100 will appear to be a waste of resources.

3. Analysis Diagram

Suppose we observe a total time of 10 seconds, which specifies 1 seconds as the minimum time interval for an event.

(1) If the frequency of the triggering event is 0.5s/, then the function stabilization,

Because there is no time to wait a second to be triggered again, so there is no final event is successful.

function throttling,

Because the control is at most one second, the frequency is 0.5s/times, so every second an event is invalidated. Final control into 1s/times.

(2) If the frequency of the triggering event is 2s/times, then

function stabilization,

Because the 2s/time is already greater than the specified minimum time, it is triggered every two seconds.

function throttling,

Similarly, 2s/times are greater than the minimum time requirement, so each trigger takes effect.

4. Application Scenario

For the function stabilization, there are several scenarios:

(1) Add a function anti-shake button to prevent the form multiple submissions.

(2) For the input box continuous input AJAX verification, the use of function stabilization can effectively reduce the number of requests.

(3) Determine if the scroll is sliding to the bottom, rolling events + function stabilization

In general, the case for multiple events, one response

For function throttling, there are several scenarios:

(1) In-game refresh rate

(2) DOM elements dragged and dragged

(3) Canvas brush function

In general, it is suitable for a large number of events to be averaged by time .

5, realize the source code:

  function Stabilization:

function Debounce (FN, wait) {varTimer =NULL; returnfunction () {varContext = This; varargs =arguments; if(timer) {cleartimeout (timer); Timer=NULL;        }; Timer=setTimeout (function () {fn.apply (context, args);    }, wait); };}varfn =function () {Console.log ('Boom');} SetInterval (Debounce (FN, -), +) //triggered after 1500ms for the first time, then once every 1000msSetInterval (Debounce (FN, -), +) //does not fire once (I see the skill reading bar of the function shake, and if the reading bar is not completed, the skill will fail and read the bar again)

A function is returned because the anti-shake itself is more like a function decoration, so it does a function of curry. The inside also uses the closure, the closure variable is the timer.

Function Throttle:

 function throttle (FN, gaptime) {Let _lasttime     = null  ;  return   function () {let _nowtime  =        Span style= "COLOR: #0000ff" >new   Date ();  if  (_nowtime-_lasttime > Gaptime | |!            _lasttime) {fn ();        _lasttime  = _nowtime;    }; };} LET fn  = () => "  Span style= "COLOR: #800000" >boom   " );} SetInterval (Throttle (FN,  1000 ), 10 );

Implementation of a simple function throttle, the result is one second hit boom.

Analysis of JS function throttling and function stabilization

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.