当前位置:网站首页>防抖函数和节流函数
防抖函数和节流函数
2022-08-05 05:29:00 【weixin_43923808】
防抖和节流区别:
防抖是将多次执行变为最后一次执行
节流是将多次执行变成每隔一段事件执行
一、什么是函数节流(throttle)
概念:限制一个函数在一定时间内只能执行一次。
举个栗子,坐火车或地铁,过安检的时候,在一定时间(例如10秒)内,只允许一个乘客通过安检入口,以配合安检人员完成安检工作。上例中,每10秒内,仅允许一位乘客通过,分析可知,“函数节流”的要点在于,在 一定时间 之内,限制 一个动作 只 执行一次 。
(1)方法一:时间戳方案
// 时间戳方案
function throttle(fn,wait){
var pre = Date.now();
return function(){
var context = this;
var args = arguments;
var now = Date.now();
if( now - pre >= wait){
fn.apply(context,args);
pre = Date.now();
}
}
}
(2)方法二:定时器方案
// 定时器方案
function throttle(fn,wait){
var timer = null;
return function(){
var context = this;
var args = arguments;
if(!timer){
timer = setTimeout(function(){
fn.apply(context,args);
timer = null;
},wait)
}
}
}
什么是函数防抖
概念:函数防抖(debounce),防抖触发高频率事件时n秒后只会执行一次,如果n秒内再次触发,则会重新计算。
举个栗子,坐电梯的时候,如果电梯检测到有人进来(触发事件),就会多等待 10 秒,此时如果又有人进来(10秒之内重复触发事件),那么电梯就会再多等待 10 秒。在上述例子中,电梯在检测到有人进入 10 秒钟之后,才会关闭电梯门开始运行,因此,“函数防抖”的关键在于,在 一个事件 发生 一定时间 之后,才执行 特定动作。
function debounce(fn,wait){
var timer = null;
return function(){
if(timer !== null){
clearTimeout(timer);
}
timer = setTimeout(fn,wait);
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener("resize",debounce(handle,1000));
边栏推荐
- uniapp打包次数限制怎么办?只需两步就能解决
- Collection of error records (write down when you encounter them)
- Transformer interprets and predicts instance records in detail
- Chengyun Technology was invited to attend the 2022 Alibaba Cloud Partner Conference and won the "Gathering Strength and Going Far" Award
- Drools规则引擎快速入门(一)
- D41_buffer pool
- Programmers should understand I/O this way
- The cocos interview answers you are looking for are all here!
- Matplotlib plotting notes
- Four ways to obtain Class objects through reflection
猜你喜欢
随机推荐
Transformer详细解读与预测实例记录
The hook of the operation of the selenium module
Network Troubleshooting Basics - Study Notes
Teach you simple steps to achieve industrial raspberries pie properly installed RS232 USB drive
ev加密视频转换成MP4格式,亲测可用
Cloud Computing Basics - Study Notes
vs2017关于函数命名方面的注意事项
txt文件英语单词词频统计
BIO,NIO,AIO实践学习笔记(便于理解理论)
Tips for formatting code indentation
数组&的运算
Collection of error records (write down when you encounter them)
Detailed explanation of ten solutions across domains (summary)
cs231n学习记录
Quick Start to Drools Rule Engine (1)
The use of three parameters of ref, out, and Params in Unity3D
el-progress implements different colors of the progress bar
reduce()方法的学习和整理
Pytorch分布式并行处理
设置文本向两边居中展示