JS関数アンチシェイクおよび関数スロットル

1.関数アンチシェイク:イベントがn秒トリガーされた後にコールバックが実行されます。このn秒以内に再度トリガーされると、タイマーが再計測されます。

function debounce(fun,delay) {
    return function(){
        let that = this;
        let args = arguments;
        clearTimeout(fun.timerId);
        fun.timerId  = setTimeout(function(){
            fun.apply(that, args);
        }, delay);
    }
}

function ajax(){...}
let ajaxDebounce = debounce(ajax, 500);
inputA.addEventListener('keyup', function(e){
    ajaxDebounce(e.target.value);
});

2.関数スロットリング:関数は単位時間内に1回しかトリガーできないと規定されています。この単位時間内に複数の関数がトリガーされた場合、その関数は1回だけ有効になります。

function throttle(fun, delay) {
    let last, deferTimer;
    return function() {
        let that = this;
        let args = arguments;
        let now = +new Date();
        if(last && last < now + delay) {
            clearTimerout(deferTimer);
            deferTimer = setTimeout(function(){
                last = now;
                fun.apply(that, args);
            }, delay);
        }else{
            last = now;
            fun.apply(that, args);
        }
    }
}

function ajax(){...}
let ajaxThrottle = throttle(ajax, 500);
inputA.addEventListener('keyup', function(e){
    ajaxThrottle(e.target.value);
});

 

公開された35元の記事 ウォンの賞賛1 ビュー6718

おすすめ

転載: blog.csdn.net/qq_36162529/article/details/103299917