函数节流:一个函数执行一次后,只有大于设定的执行周期后才会执行第二次。
应用场景:
节流函数:有一个需要频繁触发的函数,处于性能优化的角度,只让函数出发的第一次生效,后面不生效。
<script type="text/javascript">
/*
fn:要节流的函数
delay:规定的时间
*/
window.onload = function () {
function throttle (fn,delay) {
// 记录上一次的触发时间
var lastTime = 0;
console.log("throttle 里的this",this) // window
// 通过闭包可以记录上一次的lastTime
return function () {
var nowTime = Date.now();
if(nowTime - lastTime > delay){
// 修正this指向将fn()的this由window改为document
fn.call(this);
console.log("return 里的this",this) // document
// 同步时间
lastTime = nowTime;
}
}
}
document.onscroll = throttle(function () {
console.log("滚呐滚~~~~",Date.now(),"onscroll里this",this) // document
},3000)
}
</script>
当时间间隔大于3000ms时才会再次触发函数。
防抖函数:一个需要频繁触发的函数在规定的时间内,只让最后一次生效,前面的都不生效。
<script type="text/javascript">
window.onload = function () {
var btn = document.getElementById('btn');
function debounce (fn,delay) {
// 记录上一次的延时器
var timer = null;
return function () {
// 清除上一次的延时器
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(this)
},delay)
}
}
btn.onclick = debounce(function () {
console.log("确定啦~~~~",Date.now())
},2000)
}
</script>
无论在两秒内连续点击多少次按钮,都不会执行打印语句,只在最后一次点击之后再等待两秒后才会执行打印语句。