debounce、throttle、requestAnimationFrame

今天review同事代码,代码实现了返回顶部的功能,用到了lodash库中的throttle,我看着眼生,于是乎去看了下lodash文档,然后牵出了debounce,具体的知识点,这里不再赘述,底部的文章链接,是一篇很不错的文章。

下面是throttle 和 requestAnimationFrame实现的一个小功能,我只是摘抄出来,方便后面查阅。(文章底部链接的文章中也有的哈)

var latestKnownScrollY = 0,
    ticking = false,
    item = document.querySelectorAll('.item');

/// requestAnimationFrame
function update() {
    // reset the tick so we can
    // capture the next onScroll
    ticking = false;

    item[0].style.width = latestKnownScrollY + 100 + 'px';
}
function onScroll() {
    latestKnownScrollY = window.scrollY; //No IE8
    if(!ticking) {
        requestAnimationFrame(update);
    }
    ticking = true;
}
window.addEventListener('scroll', onScroll, false);

/// THROTTLE
function throttled_version() {
    item[1].style.width = window.scrollY + 100 + 'px';
}
window.addEventListener('scroll', _.throttle(throttled_version, 16), false);

https://css-tricks.com/debouncing-throttling-explained-examples/

原文地址:https://www.cnblogs.com/clover77/p/9366016.html