js implements anti-shake and throttling

Anti-
shake The function will only be executed once n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time will be recalculated;

 function debounce(func, wait) {
    
    
            let timer = null;

            return function () {
    
    
                if (timer) {
    
    
                    clearTimeout(timer);
                    timer = null;
                }

                let self = this;
                let args = arguments;

                timer = setTimeout(function () {
    
    
                    func.apply(self, args);
                    timer = null;
                }, wait);
            };
        }

Throttle
High-frequency event triggers, but only executes once in n seconds, so throttling will dilute the execution frequency of the function

function throttle(func, wait) {
    
    
            let lastTime = 0;
            let timer = null;

            return function () {
    
    
                if (timer) {
    
    
                    clearTimeout(timer);
                    timer = null;
                }

                let self = this;
                let args = arguments;
                let nowTime = +new Date();

                const remainWaitTime = wait - (nowTime - lastTime);

                if (remainWaitTime <= 0) {
    
    
                    lastTime = nowTime;
                    func.apply(self, args);
                } else {
    
    
                    timer = setTimeout(function () {
    
    
                        lastTime = +new Date();
                        func.apply(self, args);
                        timer = null;
                    }, remainWaitTime);
                }
            };
        }

Guess you like

Origin blog.csdn.net/weixin_43989656/article/details/129683369