JS 节流阀

参考 https://github.com/hahnzhu/read-code-per-day/issues/5

节流阀

节流阀的基本原理

事件函数的执行都记下当前时间, 只有当前时间与上次执行时间有一定间隔的时候才会去执行真正的逻辑

    function throttleMe(cb){
console.log('move');
var start = +new Date();
return function(){
var now = new Date();
if(now - start > 1000){
start = now;
cb();
}
}
}
$(window).on('mousemove', throttleMe(function(){
console.log('timer');
}));

有的书上是这么实现的 这个并不好用

var resizeTimer = null;
$(window).on('mousemove', function (e) {
console.log('move');
/* 第一次访问,不存在 resizeTimer,跳过这里 */
if (resizeTimer) {
clearTimeout(resizeTimer);
}
/* 第一次访问,赋值给 resizeTimer,绑定的函数 400ms 后调用 */
resizeTimer = setTimeout(function(){
console.log("move timer" /*+ e.clientX + '-' + e.clientY*/ );
}, 40);
});

发现实际中并不是40ms调用一次move timer

原因就在于timeout 它是等这个函数执行完之后间隔40ms 才有机会去执行下一个函数

    function throttle(func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = +new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = +new Date();
var remaining = wait - (now - previous); //距离下次执行剩余时间
console.log('remaining'+remaining + 'now'+ now);
context = this;
args = arguments;
if (remaining <= 0) { //过了间隔时间段 开始执行
clearTimeout(timeout);
timeout = null;
previous = now;
console.log('<0<0<0');
result = func.apply(context, args);
} else if (!timeout) {
console.log('set time out------------');
timeout = setTimeout(later, remaining);
}
return result;
};
}

函数去抖

    function debounce(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function() {
console.log('move');// 这个函数是mousemove事件处理的函数
var context = scope || this; var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function() {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
$('body').on('mousemove', function() {
console.log('move');
});
$('body').on('mousemove', debounce(function(event) {
console.log('tick');
}, 1000));

每次mousemove都是在执行 debounce返回的一个函数

这个返回的函数用到了debounce中的一个变量last

奇怪! 这个last 又不是全局的变量 为什么这个函数每次执行都依赖上次last的结果? 因为这里是一个闭包

通过闭包 使局部变量变成全局变量

因为这个a后面一直被fun函数使用 所以这个变量不会被销毁 正是闭包特性

function closure(){
var a = 1;
return function(){
return ++a;
}
}
fun = closure();
console.log(fun());//2
console.log(fun());//3
console.log(fun());//4

JS 节流阀的更多相关文章

  1. CSS3+JS切割轮播图

    以下说明数据,是指有4张图片的轮播图,分别切割成4张. 首先,做成单张切换的立体效果,即通过旋转,确定四张图片的位置,分别是一个立方体的上下前后的图片翻转移动角度. .box ul li:nth-ch ...

  2. 原生JS面向对象思想封装轮播图组件

    原生JS面向对象思想封装轮播图组件 在前端页面开发过程中,页面中的轮播图特效很常见,因此我就想封装一个自己的原生JS的轮播图组件.有了这个需求就开始着手准备了,代码当然是以简洁为目标,轮播图的各个功能 ...

  3. 读书笔记-你不知道的JS中-promise

    之前的笔记没保存没掉了,好气,重新写! 填坑-- 现在与将来 在单个JS文件中,程序由许多块组成,这些块有的现在执行,有的将来执行,最常见的块单位是函数. 程序中'将来'执行的部分并不一定在'现在'运 ...

  4. js:基于原生js的上啦下啦刷新功能

    链接:https://www.jianshu.com/p/a8392115e6f0演示地址:http://wonghan.cn/iscroll-demo/html:<body> <d ...

  5. underscore.js学习笔记

    一.理清概念 1.Underscore封装了常用的JavaScript对象操作方法,用于提高开发效率,Underscore还可以被使用在Node.js运行环境.从API中,你已经可以看出,Unders ...

  6. Underscore.js实用插件

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象. 他解决了这个问题:“如果我面对一个空白的 HTML ...

  7. JavaScript (JS)基础:DOM 浅析 (含数组Array、字符串String基本方法解析)

    ①文本对象document: 例如:document.getElementById()    只获取一个对象          document.getElementsByTagName()   获取 ...

  8. 原生JS实现动画函数的封装

    封装了一个JS方法,支持元素的基本动画:宽.高.透明度...等,也支持链式动画和同时运动. 获取元素的属性的函数并进行了兼容性处理: function getStyle(obj, attr) { if ...

  9. js实现完整轮播

    1.封装一个简单的动画函数 function animate(obj,target,callback){ clearInterval(obj.timer);//清除定时器防止定时器重复添加 obj.t ...

随机推荐

  1. static和extern关键字 对函数的作用

    本文目录 • 一.extern与函数 • 二.static与函数 • 三.static.extern与函数的总结说明:这个C语言专题,是学习iOS开发的前奏.也为了让有面向对象语言开发经验的程序员,能 ...

  2. this指针与function变量--this究竟指向哪里?

    参考文章:<深入浅出 JavaScript 中的 this> http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/ Ja ...

  3. 联系InfoSphere Streams和OpenMI时对水利模型联系的设计模式的一些考虑

    从<时序计算通用模型接口 OpenMI开发技术及应用>一书中的第一章的对接口要求描述,我想到InfoSphere streams的流数据处理模式刚好可以满足这种模型/数据之间对接的需求. ...

  4. C#实现微信开发

    C#实现微信开发前奏 不想废话,直接写了!因为是留给自己做随笔的,所以大神们看到别喷…… 1.必须有微信公众账号 2.你也可以申请测试微信号,链接给你   http://mp.weixin.qq.co ...

  5. /etc/security/limits.conf 配置

    <pre name="code" class="python">* soft nofile 65535 * hard nofile 65535 * ...

  6. HDU 5811 Colosseo(拓扑排序+单调DP)

    [题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=5811 [题目大意] 给出 一张单向图,现在将其划分成了两个部分,问划分之后的点是否分别满足按照一定 ...

  7. Ubuntu adb devices 出现??? no permissions 的解决方法

    在ubuntu 12.10下运行adb devices出现: List of devices attached ???????????? no permissions 1.用命令:   lsusb 以 ...

  8. 面向对象程序设计-C++_课时24多态的实现

    所有带virtual的类的对象,里面最上面有一个隐藏的指针vptr,指向一张表vtable #include <iostream> using namespace std; class A ...

  9. javascript编辑器预览模式解密

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. PHP 操作redis 详细讲解转的

    http://www.cnblogs.com/jackluo/p/3412670.html phpredis是redis的php的一个扩展,效率是相当高有链表排序功能,对创建内存级的模块业务关系 很有 ...