1. Handwriting anti-shock function (debounce)

Anti – shake function

The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset.

A search box, for example, doesn’t send requests when the user keeps typing. A request is sent only if the user has not entered anything for a period of time. If the input continues for less than T, the time T is recalculated and the request is not sent. This reduces the number of requests to be sent, improves performance and improves user experience.

Realize the anti – shake function

// func is a function that the user passes in to be buffed
// wait indicates the waiting time. If no parameter is sent, the default value is 50ms
const debounce = (func, wait = 50) = > {
    // Cache a timer
    let timer = null;
    // Returns the function that the user actually calls each time
    return (. args) = > {
        // Clear the last timer if it has already been set
        if (timer) clearTimeout(timer);
        // Start a new timer to delay the execution of the user-passed method
        timer = setTimeout(() = > {
            func.apply(this, args);
        }, wait);
    };
};
Copy the code

Implementation effect

Upper input box, lower display area, continuous input content, the lower display area will not update. The lower display area will update the content only if the content is not entered within 1s.

2. Handwriting throttle

Throttling function

Specifies that a function can fire only once per unit of time. If more than one function is fired in this unit of time, only one function will take effect.

Implement throttling function

// func is a function that the user passes in to be buffed
// wait indicates the waiting time. If no parameter is sent, the default value is 50ms
const throttle = (func, wait = 50) = > {
    // The last time this function was executed
    let lastTime = 0;
    // The function returned is the throttling function that the user actually calls each time
    return (. args) = > {
        // Get the current time and convert it to number
        let now = +new Date(a);// Compare the current time to the last time the function was executed
        // If the difference is greater than the set wait time, the function is executed
        if (now - lastTime > wait) {
            // Resets the last time this function was executed
            lastTime = now;
            func.apply(this, args); }}; };Copy the code

Implementation effect

Upper input box, lower display area. When continuously entering content, the display area below will only update every 500ms.