function throttling and function jitter in JavaScript

Source: Internet
Author: User

to try with a question

First we need to know why we use function throttling and functions to shake? We carry out the analysis with the following questions!

1. What events (change, blur, keyup, Etc.) will you use for the search box? To do what effect?
2. for example, scroll scrolling event, how to trigger? is rolling a distance trigger once? Or do you roll the trigger once? or roll one trigger at a time?
3. How does the MouseOver event trigger?
......

Scene Instances

function throttling and dithering appear in the scene, usually accompanied by the client DOM event Monitoring. For example, to implement a native Drag-and-drop function (which cannot be used with the H5 Drag&drop API), you need to listen to the MouseMove event all the way, get the current position of the element in the callback, and reset the location of the DOM (style changes). If we do not control, the number of callbacks triggered by moving a certain pixel is very alarming, and the callback is accompanied by DOM manipulation, which in turn causes the browser to rearrange and redraw, the poor performance of the browser may be directly suspended animation, such a user experience is very bad. What we need to do is to reduce the frequency of triggering the callback, such as Let it 500ms trigger once, or 200ms, or even 100ms, this threshold value can not be too big, too big drag will be distorted, not too small, too small version of the browser may be suspended animation, such a solution is function throttling, The English name is called " Throttle". The core of the function throttling is to let a function not execute too frequently and reduce some too fast calls to Throttle.

After saying the function throttle, then see its good base friend function to shake (debounce). Think of such a scene, for the browser window, every time the resize operation, send a request, It is clear that we need to listen to the resize event, but like mousemove, each zoom out (or Enlarge) a browser, actually trigger N multiple resize events, with throttling? Throttle can only guarantee the timing of the trigger, we are good at once, this will be used to Shake. Simply put, a function shake is a continuous function call for a certain period of time, only to be executed Once.

Example Learn

let 's take a look at the following Throttle (throttle) and debounce (shake)

1.throttle throttling, Scroll and mouseover or other ways, each move will trigger the code effect, but these effects are too dense, occupy the system resources, computer computing power is limited, we write code should be as elegant as Possible.
2.debounce to shake, the original intention is to shake from the button, so that our users after the correct operation to execute the code, and will only execute once, such as when we do text input, if we use KeyUp we are not to throttle, but to judge the user stopped the Input.
3. Throttling guarantee can only be triggered once within a certain period of time. If we just trigger it once, it's going to Shake. The code to see the gap is not very large.

Try it directly:

// first a problematic code window.onscroll=function() {    console.log (new  Date ());}

The console will Print:

VM109:2 Sun Mar 18:05:50 gmt+0800 (china standard Time) VM109:2 Sun Mar 18:05:50 gmt+0800 (china Standard Time) VM109:2 Sun Mar 18:05:50 gmt+0800 (china standard Time) VM109:2 Sun mar-18:05:50 gmt+0800 (china standard Time) VM10 9:2 Sun Mar 18:05:50 gmt+0800 (china standard Time) VM109:2 Sun Mar 18:05:50 gmt+0800 (china Standard Time)
...

The console will always be typed, and that's the problem, it's not what we want, we don't want him to keep triggering.

We want to solve these problems, so look directly at the Code:

//Let's start with a throttle, output once per second .Window.onscroll=function(){    if(window.onscrolltag = =Undefined) {window.onscrolltag=true; Console.log (NewDate ()); SetTimeout (function() {window.onscrolltag=undefined; },1000); }}//Trigger FirstWindow.onscroll=function(){    if(window.onscrolltag = =Undefined) {window.onscrolltag=settimeout (function() {window.onscrolltag=undefined; Console.log (NewDate ()); },1000); }}//Post-trigger//as you can see from the code above, we change the tag to not be available when an event is Executed. The operation can be triggered again after one second. //we're trying to shake it.Window.onscroll=function(){    if(window.onscrolltag! =Undefined)    {cleartimeout (window.onscrolltag); } Window.onscrolltag=settimeout (function() {console.log (NewDate ()); },1000);}//Shake it, Shake it, feel better listening
//throttlingfuntion Throttle (func, Wait) {varLasttime = 0, timeout; returnfuntion () {varContext = this, args=arguments, Delay= Wait | | 100, now=NewDate (). getTime (); if(now-lasttime <=Delay) {return; } lasttime=now ;          Cleartimeout (timeout); Timeout= SetTimeout (function() {timeout=NULL;        Func.apply (context, args); }, delay)}}//Shake it.functiondebounce (func, Wait) {vartimeout; return function() {        varContext = this, args=arguments, Delay= Wait | | 250;        Cleartimeout (timeout); Timeout= SetTimeout (function() {timeout=NULL;        Func.apply (context, args);    }, delay); };}

Throttle Application Scenarios

What are the application scenarios for function throttling? When do we need a time interval to trigger callbacks to control the frequency of function calls?

    • Drag-and-drop functionality for DOM elements (mousemove)
    • Shooting game Mousedown/keydown event (only One bullet can be fired per unit of Time)
    • Calculate the distance of the mouse movement (mousemove)
    • Canvas Simulation artboard Feature (mousemove)
    • Search Lenovo (keyup)
    • Monitor scrolling event to determine whether to automatically load more at the bottom of the page: after adding debounce to the scroll, only the user stops scrolling to determine whether the bottom of the page is reached or not, and if it is throttle, it will be judged once when the page Scrolls.
Debounce Application Scenarios

What are the application scenarios for function jitter? When do we need to perform a callback only once for continuous event response?

    • Trigger Statistics Events per Resize/scroll
    • Validation of text input (send AJAX requests for verification after continuous input of Text)
Summary

The core of function throttling and function dithering is to restrict a method from being triggered frequently, and a method is frequently triggered, in most cases because of a listener callback for DOM events, which is also a function throttling and chattering scenario.

If you are interested, please refer to the following: http://underscorejs.org/

function throttling and function jitter in JavaScript

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.