两者之间区别:防抖是频繁条件下只是执行一次,节流的话就是多少秒执行一次。
防抖
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"</script>
<script type="type/javascript">
$(function(){
$("#ipt").on("keyup",debounce(function(){
$(".text").text($(this).val()) //频繁操作之后,在text下面更新文本
},1000))
})
function debounce(fn,defg){
let timeout;
timeout = setTimeout(() => {
fn.call(this,arguments) //把this指向#ipt,跟函数参数argument
},defg)
}
</script>
<body>
<input type = "text" id= "ipt" placehoder = "请输入。。。"></input>
<p class="text"></p>
</body>
节流
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"</script>
<script type="type/javascript">
box.addEventListener("click",throttle(function(){
this.innerText = parseInt(this.innerText)+1
},500));
function throttle(callback,delate){
var lastDate;
return function(){
var frist;
if(lastDate ==undefined){
lastDate == new Date();
frist =true;
console.log("haha")
}
var nowDate =new Date();
if( nowDate-lastDate>delate || frist == true){
//超过一定的时间间隔就可以执行函数
callback.apply(this,arguments);
//更新lastDate的时间,给下一次触发使用
lastDate = nowDate;
}
}
}
</script>