What is function anti – shake and throttling?

Function throttling and function stabilization, both of which are a means of optimizing js code for high frequency execution.

Definition:

  • Anti-shake: this event will be executed after n seconds. If it is triggered repeatedly within N seconds, the timer will be reset
  • Throttling: only run once within n seconds. If triggered repeatedly within N seconds, only run once

The difference between

Similarities:

  • Both can be implemented using setTimeout
  • The goal is to reduce the frequency of callbacks. Saving computing Resources

Difference:

  • Function stabilization, handling callbacks after a sequence of operations, using clearTimeout and setTimeout. Function throttling, used to improve performance during high frequency events that are executed only once at a time during a continuous operation.
  • Function chattering focuses on events that are triggered consecuentially over a period of time and are executed only once last, whereas function throttling is executed only once over a period of time.

Image stabilization

Simple implementation

function debounce(func, wait) {
    let timeout;

    return function () {
        let context = this; // Save this point
        let args = arguments; // Get the event object

        clearTimeout(timeout)
        timeout = setTimeout(function(){ func.apply(context, args) }, wait); }}Copy the code

If you need to perform this operation immediately, add the third parameter

function debounce(func, wait, immediate) {

    let timeout;

    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout); // timeout is not null
        if (immediate) {
            letcallNow = ! timeout;// It will be executed immediately for the first time, and will be triggered again only after the event is executed
            timeout = setTimeout(function () {
                timeout = null;
            }, wait)
            if (callNow) {
                func.apply(context, args)
            }
        }
        else {
            timeout = setTimeout(function () { func.apply(context, args) }, wait); }}}Copy the code

The throttle

Throttling can be done using a timestamp and timer notation

With timestamps, the event is executed immediately and there is no way to execute again after the trigger is stopped

function throttled1(fn, delay = 500) {
    let oldtime = Date.now()
    return function (. args) {
        let newtime = Date.now()
        if (newtime - oldtime >= delay) {
            fn.apply(null, args)
            oldtime = Date.now()
        }
    }
}
Copy the code

If the timer is used, the timer is executed for the first time after the delay is milliseconds, and the timer is executed again after the event is stopped for the second time

function throttled2(fn, delay = 500) {
    let timer = null
    return function (. args) {
        if(! timer) { timer =setTimeout(() = > {
                fn.apply(this, args)
                timer = null}, delay); }}}Copy the code

You can combine the features of timestamp writing with those of timer writing to achieve a more precise throttling.

function throttled(fn, delay) {
    let timer = null
    let starttime = Date.now()
    return function () {
        let curTime = Date.now() // The current time
        let remaining = delay - (curTime - starttime)  // How much extra time is left since last time
        let context = this
        let args = arguments
        clearTimeout(timer)
        if (remaining <= 0) {
            fn.apply(context, args)
            starttime = Date.now()
        } else {
            timer = setTimeout(fn, remaining); }}}Copy the code

Application scenarios

Throttling performs a callback at intervals in the following scenarios:

  • Scroll to load, load more or roll bottom to listen
  • Search box, search associative functions

Shudder in successive events that only need to trigger a callback scenario are:

  • The search box searches for input. The user only needs to type one last time before sending the request
  • Mobile phone number, email verification input detection
  • Window size resize. Just after the window adjustment is complete, calculate the window size. Prevent repeated rendering.