Throttle

Every time, only one event is performed.

There are two main ways to achieve, one is to use the timestamp, one is to set the timer.

Using the timestamp

When the event is triggered, we fetch the current timestamp and subtract the previous timestamp (the first start value is set to 0). If the time period is greater than the set time period, the function is executed and the timestamp is updated. Of the timestamp, if less than, do not perform.

Function throttle (func, wait) {
    Var context, args;
    Var previous = 0;

    Return function () {
        Var now = + new Date ();
        Context = this;
        Args = arguments;
        If (now - previous> wait) {
            Func.apply (context, args);
            Previous = now;
        }
    }
}

Use the timer

Set a timer, and then trigger the event, if the timer exists, do not execute until the timer is executed, and then execute the function, clear the timer, so you can set the next timer.

Function throttle (func, wait) {
    Var timeout;
    Return function () {
        Context = this;
        Args = arguments;
        If (! Timeout) {
            Timeout = setTimeout (function () {
                Timeout = null;
                Func.apply (context, args)
            }, Wait)
        }

    }
}

🤓