节流、防抖

防抖

场景:

function scrollHandle() {
    console.log("滑动。。。。")
}

function debounce(fn, wait) {
    let timer = null;
    return function() {
        if(timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(fn, wait)
    }
}
window.addEventListener('scroll', debounce(scrollHandle, 800))

节流

function throttle(fn, wait) {
    var valid = true;
    return function() {
        if(!valid) {
            return false;
        }
        valid = false
        setTimeout(() => {
            fn();
            valid = true
        }, wait);
    }
}

function showTop  () {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  console.log('滚动条位置:' + scrollTop);
}
window.onscroll = throttle(showTop,1000) 

场景