码迷,mamicode.com
首页 > 其他好文 > 详细

【源码】防抖和节流源码分析

时间:2018-10-20 16:57:17      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:amp   闭包   大小   原理   ons   net   函数库   .net   函数   

前言

防抖、节流主要用于频繁事件触发,例如鼠标移动、改变窗口大小等。lodash等函数库具备相对应的api_.debounce_.throttle

核心技术:闭包。

区别:

  • 防抖, 连续触发, 第一次和最后一次触发有效
  • 节流, 一段时间内仅触发一次(第一次)

本文以防抖函数为例, 详细说明。

实现

原理, 计时器存储状态。

function debounce(fn, delay) {
    return function() {
        console.log(fn.timer, count2);
        let _this = this;
        let _args = arguments;
        fn.timer !== undefined && clearTimeout(fn.timer);
        fn.timer = setTimeout(function() {
            fn.apply(_this, _args);
        }, delay);
    }
}
// 替换
debounce(oldFunction, delay)();

改进, 可多处调用

/**
 * 防抖函数
*/
function debounce(fn, delay) {
    let timer;
    return function () {
        let _this = this;
        let _args = arguments;
        console.log(timer, count2)
        timer !== undefined && clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(_this, _args);
        }, delay);
    }
}
var newFucntion = debounce(oldFunction, delay);
// 替换
newFunction();

我的测试连接, 打开控制台查看

参考

灵感-薄荷周刊, 有错误, 仅供参考

参考blog

参考演示

【源码】防抖和节流源码分析

标签:amp   闭包   大小   原理   ons   net   函数库   .net   函数   

原文地址:https://www.cnblogs.com/daaasheng/p/9822193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!