关于防抖节流基础介绍及基础实现参见上篇博客:函数防抖与节流,本节为扩展功能源码
防抖源码封装:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" name="">
<button>取消</button>
</body>
<script type="text/javascript">
function debounce(fun,time,flag){
//该函数三个参数,第一个参数fun为回调函数,time为等待的时间,flag为ture表示先运行回调函数在等待,反之先等待在运行
var timer = null;
var debounced = function(){
var _this = this;
var arg = arguments;
clearTimeout(timer);
if(flag){ //一输入就触发回调函数,然后等待规定的时间
if(!timer){
fun.apply(_this,arg);
}
timer = setTimeout(function(){timer = null},time);
}else{ // 输入等待后在触发回调函数
timer = setTimeout(function() {
fun.apply(_this,arg);
}, time);
}
}
debounced.cancel = function(){ //取消的方法
clearTimeout(timer);
timer = null;
}
return debounced;
}
function callback(e){
console.log(this.value);
console.log(e.target);
}
var input = document.getElementsByTagName("input")[0];
var btn = document.getElementsByTagName("button")[0];
var setUseAction = debounce(callback,1000,false);
input.oninput = setUseAction;
btn.onclick = setUseAction.cancel;
</script>
</html>
节流源码封装
- 时间戳法
function throttle(func,time){
var lastTime = 0;
return function(){
var newTime = +new Date();//获取时间戳
if(newTime - lastTime >= time){
func.apply(this,arguments);
lastTime = newTime;
}
}
}
- 定时器法
function thottle(func,time){
var timer = null;
return function(){
var _this = this;
var arg = arguments;
if(timer){
timer = SetTimeout(function(){
func.apply(_this,arg);
timer = null; //timer只是变量,直接赋值为null并不能停止计时器
},time);
}
}
}