当前位置:网站首页>js函数防抖和函数节流及其使用场景
js函数防抖和函数节流及其使用场景
2022-08-04 00:17:00 【Kⅈꫛᧁ269】
一、函数防抖
1、概念
频繁触发,但只在特定的时间内才执行最后一次触发的函数
function debounce(callback, time) {
let t;
return function () {
clearTimeout(t);
t = setTimeout(callback, time);
}
}
window.onscroll = debounce(function(){
console.log("调用一次");
},500)
2、使用场景
一般是用来,用户输入有操作时,暂时不执行动作,等待没有新操作时,进行相应响应,例如用户名输入校验的情况,可以等待用户输入完成后再发送请求去校验。
3、函数防抖的实现
(1)未使用防抖函数的情况
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>测试</title>
</head>
<body>
<div id="dom"></div>
</body>
<script> // 当前dom节点插入p标签,让浏览器当前窗口出现滚动条 let dom = document.getElementById("dom"); for(let i = 0 ; i < 20 ; ++i){
let node = document.createElement("p"); node.innerText = i; dom.appendChild(node) } function getScrollTop(){
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop; console.log("滚动条位置:" + scrollTop); }; window.onscroll = this.getScrollTop(); //window.onscroll = this.throttle(this.getScrollTop(), 1000); //节流 //window.onscroll = this.debounce(this.getScrollTop(), 1000); //防抖 </script>
</html>
测试:
(2)使用防抖函数
代码如下:
/*
+需求:监听浏览器滚动事件,返回当前滚动条与顶部之间的距离
+防抖实现原理如下:
+前提条件:在第一次触发事件时,不立即执行函数,而是给出了一个期限值,比如200ms,然后:
1. 如果在200ms内没有再次触发滚动事件,那么就执行函数
2. 如果在200ms内再次触发滚动事件,那么当前的计时取消,重新开始计时
+效果:如果短时间内大量触发同一事件,只会执行一次函数
+实现:使用setTimeout函数,借助闭包实现
*/
/*
fn [function] 需要防抖的函数
delay [number] 毫秒,防抖期限值
*/
<!DOCTYPE html>
<html lang="en">
<head>
<title>测试</title>
</head>
<body>
<div id="dom"></div>
</body>
<script> function debounce(fn, delay){
let timer = null; // 借助闭包 return function(){
if(timer){
clearTimeout(timer) //进入该分支,说明当前正在一个计时过程中,并且又触发了相同事件 } timer = setTimeout(fn,delay) //表示没有当前没有进行计时,开始一个新计时 } } </script>
</html>
二、函数节流
1、概念
频繁触发,但只在特定的时间内才执行第一次触发的函数
function throlle(callback, time) {
let lasttime = new Date().getTime();
return function () {
let nowtime = new Date().getTime();
if (nowtime - lasttime > time) {
callback();
lasttime = nowtime;
}
}
}
window.οnscrοll=throlle(function(){
console.log("调用了1次");
},1500)
2、使用场景
一般是用在必须执行这个动作,但是不能够执行太频繁的情况下,例如滚动条滚动时函数的处理,可以通过节流适当减少响应次数;
window.onscroll = function(){
console.log("要执行的事");
}
3、函数节流的实现
(1)未使用节流函数的情况
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>测试</title>
</head>
<body>
<div id="dom"></div>
</body>
<script> // 当前dom节点插入p标签,让浏览器当前窗口出现滚动条 let dom = document.getElementById("dom"); for(let i = 0 ; i < 20 ; ++i){
let node = document.createElement("p"); node.innerText = i; dom.appendChild(node) } function getScrollTop(){
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop; console.log("滚动条位置:" + scrollTop); }; window.onscroll = this.getScrollTop(); //window.onscroll = this.throttle(this.getScrollTop(), 1000); //节流 //window.onscroll = this.debounce(this.getScrollTop(), 1000); //防抖 </script>
</html>
测试:
(2)使用节流函数
/*
+需求:监听浏览器滚动事件,返回当前滚动条与顶部之间的距离
+节流实现原理如下:
+前提条件:即使用户不断拖动滚动条,也能在固定的某个时间间隔之后给出滚动条与顶部之间的距离
+效果:如果短时间内大量触发同一事件,那么在函数执行一次之后,该函数在指定的时间期限内不工作,甚至过了这段时间才重新生效。【假如设置的delay = 1000ms,那么如果在短时间内大量触发同一事件,则每隔 1000ms 执行一次该事件函数。】
+实现:使用setTimeout函数,加上状态位valid来实现
*/
/*
fn [function] 需要节流的函数
delay [number] 毫秒,节流期限值
*/
// 方式一:采用时间戳的方式
<!DOCTYPE html>
<html lang="en">
<head>
<title>测试</title>
</head>
<body>
<div id="dom"></div>
</body>
<script> function throttle(fn, interval){
let last = null; let now = new Date(); let timer = null; return function(){
if(last && now - last < interval){
clearTimeout(timer); timer = setTimeout(()=>{
fn(), last = now; },interval); }else{
last = now; } } } // 方式二:采用状态位 function throttle(fn, interval) {
let valid = true; return function() {
if (!valid) return false; // 休息中 // 工作时间,执行函数并且在间隔时间内把状态设置为无效 valid = false; setTimeout(() => {
fn(), (valid = true); }, interval); }; } // 方式三:判断当前定时器是否存在,如果存在表示还在冷却,并且在执行定时器fn之后消除定时器 function throttle(fn, interval) {
let timer = null; return function() {
if (timer) return false; timer = setTimeout(() => {
fn(); clearTimeout(timer) timer = null }, interval); }; } </script>
</html>
边栏推荐
- Talking about the future development direction of my country's industrial parks
- leetcode/子串中不能有重复字符的最长子串
- 咱们500万条数据测试一下,如何合理使用索引加速?
- - the skip/skipif Pytest learning
- Spinnaker调用Jenkins API 返回403错误
- 带你造轮子,自定义一个随意拖拽可吸边的悬浮View组件
- 全面讲解 Handler机制原理解析 (小白必看)
- Justin Sun: Web3.0 and the Metaverse will assist mankind to enter the online world more comprehensively
- LeetCode 0155. 最小栈
- 【每日一题】899. 有序队列
猜你喜欢
win10+cuda11.7+pytorch1.12.0安装
ping数据包中的进程号
nodeJs--async/await
第1章:初识数据库与MySQL----MySQL安装
一文参透分布式存储系统Ceph的架构设计、集群搭建(手把手)
YOLOv7改进之二十二:涨点神器——引入递归门控卷积(gnConv)
"Miscellaneous" barcode by Excel as a string
LeetCode 19:删除链表的倒数第 N 个结点
【杂项】如何将指定字体装入电脑然后能在Office软件里使用该字体?
Nanoprobes Alexa Fluor 488 FluoroNanogold 偶联物
随机推荐
超级完美版布局有快捷键,有背景置换(解决opencv 中文路径问题)
【MySQL —— 索引】
Go编译原理系列7(Go源码调试)
HNUCM 您好中国
The super perfect layout has shortcut keys and background replacement
迭代扩展卡尔曼滤波IEKF
pcl点云数据 转化为 Eigen::Map
【性能优化】MySQL常用慢查询分析工具
View the version number of CUDA, pytorch, etc.
2022-08-03:以下go语言代码输出什么?A:2;B:3;C:1;D:0。 package main import “fmt“ func main() { slice := []i
新一代服务网关Gateway的实践笔记
Nanoprobes 棕榈酰纳米金相关说明书
七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
通过whl安装第三方包
七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
咱们500万条数据测试一下,如何合理使用索引加速?
The "interaction design" battle of the smart cockpit
ML18-自然语言处理
2023年航空航天、机械与机电工程国际会议(CAMME 2023)
Salesforce's China business may see new changes, rumors may be closing