解析underscore中的debounce
先奉上源码
取自Underscore.js 1.9.1的debounce
_.debounce = function(func, wait, immediate) {
var timeout, result;
var later = function(context, args) {
timeout = null;
if (args) result = func.apply(context, args);
};
var debounced = restArguments(function(args) {
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(this, args);
} else {
timeout = _.delay(later, wait, this, args);
}
return result;
});
debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};
return debounced;
};
其中比较陌生的是restArguments和_.delay,那么我们首先来逐个分析它们
restArguments
// Some functions take a variable number of arguments, or a few expected
// arguments at the beginning and then a variable number of values to operate
// on. This helper accumulates all remaining arguments past the function’s
// argument length (or an explicit `startIndex`), into an array that becomes
// the last argument. Similar to ES6’s "rest parameter".
var restArguments = function(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0;
for (; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
// 个人觉得这段switch没有特别意义,可以删除
// switch (startIndex) {
// case 0: return func.call(this, rest);
// case 1: return func.call(this, arguments[0], rest);
// case 2: return func.call(this, arguments[0], arguments[1], rest);
// }
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
};
它很类似ES6的剩余参数
举个例子
function sum (a, b, rest) {
var sum = a + b;
console.log(Array.isArray(rest)); // 打印true
if (rest.length) {
sum += rest.reduce((x, y) => x + y);
}
return sum;
}
ra_sum = restArguments(sum);
console.log(ra_sum(1, 2)); // 8
console.log(ra_sum(1, 2, 3, 4, 5)); // 15
// 利用ES6的剩余参数可以这样写
function es6_ra_sum(a, b, ...rest) {
var sum = a + b;
console.log(rest)
console.log(Array.isArray(rest)); // 打印true
if (rest.length) {
sum += rest.reduce((x, y) => x + y);
}
return sum;
}
console.log(es6_ra_sum(1, 2)); // 3
console.log(es6_ra_sum(1, 2, 3, 4, 5)); // 15
_.delay
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = restArguments(function(func, wait, args) {
return setTimeout(function() {
return func.apply(null, args);
}, wait);
});
// 相当于
_.delay = function(func, wait, ...args) {
return setTimeout(function() {
return func.apply(null, args);
}, wait);
}
_.debounce
_.debounce = function(func, wait, immediate) {
var timeout, result;
var later = function(context, args) {
timeout = null; // 重置timeout为了leading执行
// 判断arg是为了下面运行timeout = setTimeout(later, wait);这句话时func不会被执行
if (args) result = func.apply(context, args);
};
// 原本来是restArgumenst返回函数,这里为了直观我直接换成es6的剩余参数形式
var debounced = function(...args) {
if (timeout) clearTimeout(timeout);
if (immediate) {
//初始的时候timeout为undefined,later函数运行的时候置为null, 这两种情况callNow为true
var callNow = !timeout;
// 下面这句话的目的不是为了执行func而是切换timeout的值,也就是间接改变callNow。而且later中args并没有传入所以不会执行later中不会执行func
timeout = setTimeout(later, wait);
// 这句话才是当immediate为true时真正地执行func
if (callNow) result = func.apply(this, args);
} else {
// trailing执行func
timeout = _.delay(later, wait, this, args);
// 相当于setTimeout(function() {
// return later.apply(null, [this, args]);
// }, wait);
// 再在later中运行result = func.apply(this, args); 最后和callNow的时候运行一致
}
return result;
}
debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};
return debounced;
};
解析underscore中的debounce的更多相关文章
- 解析underscore中的throttle
什么是throttle(节流) Throttling enforces a maximum number of times a function can be called over time. 简单 ...
- 理解Underscore中的_.bind函数
最近一直忙于实习以及毕业设计的事情,所以上周阅读源码之后本周就一直没有进展.今天在写完开题报告之后又抽空看了一眼Underscore源码,发现上次没有看明白的一个函数忽然就豁然开朗了,于是赶紧写下了这 ...
- 理解Underscore中的节流函数
上一篇中讲解了Underscore中的去抖函数(_.debounced),这一篇就来介绍节流函数(_.throttled). 经过上一篇文章,我相信很多人都已经了解了去抖和节流的概念.去抖,在一段连续 ...
- 关于 underscore 中模板引擎的应用演示样例
//关于 underscore 中模板引擎的应用演示样例 <!doctype html> <html> <head> <meta charset=" ...
- 深入解析Underscore.js源码架构
Underscore.js是很有名的一个工具库,我也经常用他来处理对象,数组等,本文会深入解析Underscore源码架构,跟大家一起学习下他源码的亮点,然后模仿他写一个简单的架子来加深理解.他的源码 ...
- 浅解析js中的对象
浅解析js中的对象 原文网址:http://www.cnblogs.com/foodoir/p/5971686.html,转载请注明出处. 前面的话: 说到对象,我首先想到的是每到过年过节见长辈的时候 ...
- 深入解析Javascript中this关键字的使用
深入解析Javascript中面向对象编程中的this关键字 在Javascript中this关键字代表函数运行时,自动生成的一个内部对象,只能在函数内部使用.比如: function TestFun ...
- js中eval详解,用Js的eval解析JSON中的注意点
先来说eval的用法,内容比较简单,熟悉的可以跳过eval函数接收一个参数s,如果s不是字符串,则直接返回s.否则执行s语句.如果s语句执行结果是一个值,则返回此值,否则返回undefined. 需要 ...
- 2dx解析cocosbuilder中使用layer时的缺陷
2dx解析cocosbuilder中使用layer时的缺陷 cocos2d-x 3.7 cocosbuilder中的layer通常会用到触摸属性: 但是在2dx解析布局文件的时候,却很多属性都没解析: ...
随机推荐
- 多线程server与多client通信
鉴于ServerSocket的accept方法是阻塞的,那么只能通过多线程的方式实现多客户端连接与服务器连接 基本步骤: 1,服务端创建ServerSocket绑定端口号,循环调用accept()方法 ...
- java模式之单例
懒汉式:需要实例的时候new public class Singleton_Lazy { private static Singleton_Lazy mSingleton; private Singl ...
- 【转】python中的闭包详细解析
一.什么是闭包? 如果一个内嵌函数访问外部嵌套函数作用域的变量,并返回这个函数,则这个函数就是闭包 闭包必须满足三个条件: 1. 必须有一个内嵌函数 2. 内嵌函数必须引用外部嵌套函数中的变量 ...
- Java源码-集合-ArrayList
基于JDK1.8.0_191 介绍 在Java中,对于数据的保存和使用有多种方式,主要的目的是以更少的资源消耗解决更多的问题,数组就是其中的一种,它的特点是所有的数据都保存在内存的一段连续空间中, ...
- VMware 设置共享文件夹
1. 打开: 虚拟机 -> 设置 -> 选项 2. 选择 “总是启用” ,然后点 “添加” 选择你要共享的本地文件夹,最后点确定. 3. Linux下在 /mnt/hgfs 文件夹下就可以 ...
- 使用oracle 的 PL/Sql 定时执行一个存储过程
CSDN日报20170322--<关于软件研发的一些体会总结> 同步博客至 CSDN ,让更多开发者看到你的文章 看微博技术大咖解析互联网应用架构实战 使用oracle 的 PL/Sql ...
- Java程序基本优化
1.尽量指定类的final修饰符,因为带有final修饰符的类是不可派生的. 2.尽量重用对象. 3.尽量使用局部变量. 4.不要重复初始化变量. 5.在Java+Oracle的应用系统开发中,Jav ...
- python对文件中光标的操作迭代器
seek() 默认从文件开头开始.seek(10) seek(10,1) 需要以b的模式读取文件,从相对位置进行移动光标 seek(-3,2) 倒着移动光标的模式 例如: f= open( ...
- 【剑指Offer面试编程题】题目1514:数值的整数次方---九度OJ
题目描述: 给定一个double类型的浮点数base和int类型的整数exponent.求base的exponent次方. 输入: 输入可能包含多个测试样例. 对于每个输入文件,第一行输入一个整数T, ...
- 第1节 storm编程:9、storm与kafka的整合
详见代码. 下图,为设置kafka的首次消费策略,即首次消费的偏移量的示例: