美文网首页
防抖与节流

防抖与节流

作者: 天神9527 | 来源:发表于2020-09-14 16:18 被阅读0次

防抖

当持续触发事件时,一定时间段内没有再次触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又触发了一次,就重新开始计时

//防抖
function debounce(fn, delay) {
    var timerId = null;
    return function() {
        timerId && clearTimeout(timerId) && (timerId = null);
        timerId = setTimeout(fn, delay);
    }
}

//处理函数
function handle() {
    console.log(Math.random());
}

//滚动事件
window.addEventListener('scroll', debounce(handle, 1000));

界面滚动时,控制台没有打印内容,当停止滚动1s,控制台打印随机数

节流

当持续触发事件时,保证一定时间段内只调用一次事件处理函数

给出两种实现方式

// 1.定时器

let throttle = function(func, delay) {
    let timer = null;
    return function() {
        let args = arguments;
        if(!timer) {
            timer = setTimeout(() => {
                func.apply(this, args);
                clearTimeout(timer);
                timer = null;
            }, delay);
        }
    }
}

function handle() {
    console.log(Math.random());
}

window.addEventListener('scroll', throttle(handle, 1000));

利用定时器实现方式,和用setTimout实现setInterval的原理一样。与防抖的差别在于clearTimeout的调用和timerId的赋值处理。

  • 防抖在存在timerId时执行clearTimeout,中断定时器函数调用,并重新进行计时
  • 节流在timerId被清空后,重新进行计时
// 2.时间戳
function throttle  (func, delay) {
    let prev = Date.now();
    return function() {
        let context = this;
        let args = arguments;
        let now = Date.now();
        if (now - prev >= delay) {
            func.apply(context, args);
            prev = Date.now();
        }
    }
}

function handle() {
    console.log(Math.random());
}

window.addEventListener('scroll', throttle(handle, 1000));

相关文章

网友评论

      本文标题:防抖与节流

      本文链接:https://www.haomeiwen.com/subject/zaezektx.html