JS: Anti-jitter and throttling __javascript

Source: Internet
Author: User
Tags prev

For some frequently triggered events such as scroll, resize, if the normal binding event handler function, it is possible to repeatedly trigger events in a very short period of time, greatly affecting performance.

Therefore, for this type of event to be against jitter or throttling processing to prevent jitter

Its practice is to limit the time interval that must wait before the next function call. The way to implement debouncing correctly is to synthesize several function calls once, and only once after a given time passes.

The Debounce function
debounce (FN, delay) {//That will wrap the event to
  maintain a timer let
  timer = null;

  return function () {
    //through ' this ' and ' arguments ' gets the scope and variables of the functions let the context
    = this;
    let args = arguments;

    Cleartimeout (timer);
    Timer = settimeout (function () {
      fn.apply (context, args);
    }, delay);
  }
function Functions
foo () {
  Console.log (' You are scrolling! ')

called when the user scrolls Wrapping our function in debounce, triggering a let
elem = document.getElementById (' container ') once in 2 seconds;
Elem.addeventlistener (' scroll ', Debounce (foo, 2000));

First, we handle functions for scroll event bindings, when the Debounce function is called immediately,
So the function that is bound to the scroll event is actually the function returned within the Debounce

Each time an event is triggered, the current timer is cleared and the timeout call is reset.
This causes each High-frequency event to cancel the previous timeout call, causing the event handler to not be triggered only if the High-frequency event stops, the last event-triggered timeout call can be executed after delay time

Further, we don't want to wait until the event stops triggering before it executes, and I want to execute the function immediately, and then wait until it stops firing n seconds before the execution can be triggered again.
Here, add a immediate parameter to set whether to execute immediately:

function Debouce (func,delay,immediate) {
    var timer = null;
    return function () {
        var context = this;
        var args = arguments;
        if (timer) cleartimeout (time);
        The if (immediate) {
            //////////delay determines whether the function
            var donow =!timer is to be executed now based on whether the time of the last triggering operation is reached;
            Every time you reset the timer, you have to make sure that the
            timer = settimeout (function () {
                timer = null;
            },delay)
            can be executed at least delay seconds after each execution. Execute immediately
            if (donow) {
                func.apply (Context,args);
            }
        } else{
            timer = settimeout (function () {
                func.apply (Context,args);
            },delay);
        }
    }
}
throttling

Throttling is another way to deal with similar problems.
throttling functions allow a function to execute only once in a specified time.

The biggest difference between this and the jitter is that the throttle function, regardless of how frequently the event is triggered, guarantees that a real event handler will be executed within the specified time.

For example, in the infinite load scene of the page, we need users to scroll the page, every once in a while to send an Ajax request, rather than when the user stopped scrolling page operation to request data . This kind of scene, is suitable uses the throttle valve technology to realize.

There are two main methods of implementation: Time stamp timer

time stamp Implementation :

var throttle = function (func,delay) {
    var prev = Date.now ();
    return function () {
        var context = this;
        var args = arguments;
        var now = Date.now ();
        if (now-prev>=delay) {
            func.apply (Context,args);
            prev = Date.now ();}}

When the High-frequency event is triggered, the first time should be executed immediately (to the event binding function and the actual trigger event interval if greater than delay), and then how frequently trigger the event, will be executed every delay seconds. And when the last event is triggered, the event will not be executed again.

Timer Implementation:
When the event is triggered, we set a timer, then trigger the event, if the timer exists, do not execute; until delay seconds, the timer executes the function and empties the timer so that the next timer can be set.

var throttle = Fucntion (func,delay) {
    var timer = null;

    Return funtion () {
        var context = this;
        var args = arguments;
        if (!timer) {
            timer = settimeout (function () {
                func.apply (Context,args);
                timer = null;
            },delay);}}

When the event is first triggered, the function is definitely not executed immediately, but only after delay seconds.
The event is then continuously triggered, and it is executed every delay second.
After the last stop trigger, the function may also be executed once due to the delay delay of the timer.

You can use a combination of timestamps and timers to perform an event trigger immediately, and the throttle function can be executed once the trigger is completed:

var throttle = function (func,delay) {
    var timer = null;
    var starttime = Date.now ();

    return function () {
        var curtime = Date.now ();
        var remaining = delay-(curtime-starttime);
        var context = this;
        var args = arguments;

        Cleartimeout (timer);
        if (remaining<=0) {
            func.apply (Context,args);
            StartTime = Date.now ();
        } else{
            timer = settimeout (func,remaining);
        }
    }
}

It is necessary to perform the function once in each delay time, so the start time, the current time and the delay are used to compute the remaining within the throttle function, and the execution function is represented when remaining<=0. If it is not yet time, set the remaining time before triggering. Of course, if the event occurs again during the remaining period, the current timer is canceled and a remaining is recalculated to determine the current state. Summary

How to prevent a callback function from being triggered frequently by an event:

Anti-jitter: merges several operations into one operation. The principle is to maintain a timer that triggers the function after the delay time, but if it fires again within delay time, it will cancel the timer and reset it. As a result, only the last operation can be triggered.

Throttling: causes a function to be triggered only once in a certain amount of time.
The biggest difference between it and anti jitter is that throttling functions, regardless of how frequently the event is triggered, guarantee that a real event handler will be performed within a specified amount of time, and that the anti jitter only triggers a function once after the last event. The
principle is to trigger a function by determining whether it arrives for a certain amount of time, and if the timer is deferred if it is not specified, the next event will reset the timer.

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.