一.函数防抖
(1).特性
1.对于在事件被触发n秒后再执行的回调(延迟执行)
2.如果在这n秒内再触发事件,重新开始计时(无效触发)
(2).简单说明
var oBox = document.getElementsByClassName('box')[0];
var t = null;
oBox.onmouseover = function(){
clearTimeout(t);//如果不清除函数会一直延迟全部执行,违背第二特性
//实现第一条特性
t = setTimeout(function(){
console.log(2)
},1000);
}
(3).缺点和用处
缺点:污染全局 初次触发事件时也会延迟执行
用处:ajax请求数据/提交数据/输入验证
(4).封装
function debounce(fn, time, triggleNow){
var t = null,
res;
//这里用debounced接收是因为要写一个取消防抖的属性
var debounced = function(){
var _self = this,
args = arguments;//这里要考虑到防抖函数也可能会传参给目标函数
if(t){
clearTimeout(t);
}
if(triggleNow){
//第一次进来的时候肯定为true
var exec = !t;
//如果不写这个定时就代表我time可以实时响应违背第一条特性
//写上之后在我time内时exec会一直是false的
t = setTimeout(function(){
t = null
},time)
//常规操作
if(exec){
res = fn.apply(_self, args);
}
}else{
t = setTimeout(function(){
res = fn.apply(_self, args);
},time)
}
return res;
}
debounced.remove = function(){
clearTimeout(t);
t = null;
}
return debounced;
}
二.函数节流
(1).节流特性
1.第一次必定延迟
2.n秒之内执行一次(频繁操作也只响应固定时间内的)
function throttle(fn, delay){
var t = null,
begin = new Date().getTime();//获取开始时间
return funciton(){
var _self = this,
args = arguments,
cur = new Date().getTime();//获取结束时间
clearTimeout(t);
if(cur - begin >= delay){
fn.apply(_self, args);
strTime = curTime;
}else{
t = setTimeout(function(){
res = fn.apply(_self, args);
},delay)
}
}
}
返回一个新函数时,外层包裹的函数只执行一次
三.防抖和节流的应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
.box{
width:500px;
height:500px;
background-color: black;
}
</style>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
var oBox = document.getElementsByClassName('box')[0],
t = null;
oBox.onmouseout = throttle(show, 2000)
function show(){
console.log("1");
}
function throttle(fn, delay){
var t = null,
strTime = new Date().getTime();
return function(){
var _self = this,
arg = arguments,
curTime = new Date().getTime();
clearTimeout(t);
if(curTime - strTime >= delay){
strTime = curTime;
fn.apply(_self, arg);
}else{
t = setTimeout(function(){
fn.apply(_self, arg)
},delay)
}
}
}
function debounce(fn, time, traggleNow){
var t = null,
res;
var debounced = function(){
var _self = this,
arg = arguments;
if(t){
clearTimeout(t);
}
if(traggleNow){
var exec = !t;
t = setTimeout(function(){
t = null;
},time);
if(exec){
res = fn.apply(_self, arg)
}
}else{
t = setTimeout(function(){
res = fn.apply(_self, arg)
},time)
}
return res;
}
debounced.remove = function(){
clearTimeout(t);
t = null;
}
return debounced;
}
</script>
</body>
</html>