2.03.22防抖函数的拓展
- 根据触发函数后是否马上执行的需求设计以下防抖函数:
- js
// 防抖函数
// 首次触发事件,不需要延迟函数,就直接执行callback
// 在指定的时间(time)内,允许触发事件,事件频繁触发的情况,那就会重新计算时间(time)
// 以后调用这个防抖函数时:
// 分两种情况:1,首次触发事件,不需要延迟函数 (isFisrt == true) 2,首次触发事件,需要延迟函数(isFisrt == false)
function debounceV2(callback, time, isFisrt) {
var delay = null;
var time = time || 300;
var isFisrt = isFisrt;
return function(){//事件函数作用域
// 事件对象
var _event = arguments[0];
// 记录事件的调用者
var _this = this;
// 首次触发事件不需要延迟的逻辑
if(isFisrt){
// delay本身null (false), !null(true)
if(!delay){
// 意思是!delay 如果是false就不执行回调函数
if(callback){
callback.call(this,_event)
}
}
// 先清除延迟函数 ,然后在赋值
if(delay) clearTimeout(delay)
// delay有值 !null(false)
delay = setTimeout(function(){
// 此处重置delay,意思是!delay 结束是true ,又可以下一次执行回调函数
delay = null;
},time)
}else {
// 首次触发事件需要延迟的逻辑
// 如果!isFirst 这个布尔值,就说明首次触发事件需要延迟
if(!isFisrt){
// 先清除延迟函数 ,然后在赋值
if(delay) clearTimeout(delay);
// 执行延迟函数
delay = setTimeout(function(){
// 判断是否存在回调
if(callback){
callback.call(_this,_event);
}
},time)
}
}
}
}
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>htmlcss 阶段</title>
<style>
.box-1,
.box-2 {
width: 100px;
height: 100px;
background-color: #ccc;
margin-top: 20px;
font-size: 14px;
}
.box-1 span,
.box-2 span {
font-size: 30px;
}
</style>
</head>
<body>
<div class="box-1">盒子A: <span>0</span></div>
<div class="box-2">盒子B: <span>0</span></div>
<script src="../js/debounceV2.js"></script>//引入上面那个js文件
<script>
// 编码:
var box1 = document.querySelector(".box-1")
var box2 = document.querySelector(".box-2")
// 盒子A
var count = 0;
// 首次触发事件需要延迟
box1.onmousemove = debounceV2(function(){
count ++;
this.children[0].innerHTML = count;
},1000,false);
// 首次触发事件不需要延迟
var num = 0;
box2.onmousemove = debounceV2(function(){
num ++;
this.children[0].innerHTML = num;
},1000,true);
</script>
</body>
</html>