【JS】防抖和节流

2021-04-19  本文已影响0人  睡神疯子

防抖

概念

触发高频事件后 n 秒内函数只会执行一次,在 n 秒内高频事件多次触发只执行最后一次,每次触发 n 会重置。比如有个按钮,猛地点鼠标只会最后执行一次。

实现
//防抖debounce代码:
function debounce(fn,delay) {
    var timeout = null; // 创建一个标记用来存放定时器的返回值
    return function (e) {
        // 每当用户输入的时候把前一个 setTimeout clear 掉
        clearTimeout(timeout); 
        // 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
        timeout = setTimeout(() => {
            fn.apply(this, arguments);
        }, delay);
    };
}
function handle() {
    console.log('防抖:', Math.random());
}
window.addEventListener('scroll', debounce(handle,500));
// window.addEventListener('scroll', debounce(function(e) {
//     handle();
// },500));

节流

概念

高频事件触发,但在 n 秒内只会执行一次,稀释函数执行频率。比如有个按钮,猛地点会隔 n 秒执行一次。

实现
//节流throttle代码:
function throttle(fn,delay) {
    let canRun = true; // 通过闭包保存一个标记
    return function () {
        // 在函数开头判断标记是否为true,不为true则return
        if (!canRun) return;
        // 立即设置为false
        canRun = false;
        // 将外部传入的函数的执行放在setTimeout中
        setTimeout(() => { 
        // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
        // 当定时器没有执行的时候标记永远是false,在开头被return掉
            fn.apply(this, arguments);
            canRun = true;
        }, delay);
    };
}
function sayHi(e) {
    console.log('节流:', e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi,500));
// window.addEventListener('scroll', throttle(function(e) {
//     sayHi();
// },500));
应用场景
上一篇下一篇

猜你喜欢

热点阅读