1. 程式人生 > >js防抖節流封裝

js防抖節流封裝

cti 事件 ole del ply span 發的 fun self

/**
 * 節流函數
 * @param method 事件觸發的操作
 * @param mustRunDelay 間隔多少毫秒需要觸發一次事件
 */
function throttle(method, mustRunDelay) {
    let timer,
        args = arguments,
        start;
    return function loop() {
        let self = this;
        let now = Date.now();
        if(!start){
            start 
= now; } if(timer){ clearTimeout(timer); } if(now - start >= mustRunDelay){ method.apply(self, args); start = now; }else { timer = setTimeout(function () { loop.apply(self, args); },
50); } } } window.onscroll = throttle(function () { let scrollTop = document.body.scrollTop || document.documentElement.scrollTop; console.log(‘滾動條位置:‘ + scrollTop); },800)

js防抖節流封裝