前端性能优化——节流(throttle)
一、定义:
一个函数执行一次后,在只有大于设定的执行周期后才执行第二次,假设有个需要频繁触发的函数,处于性能优化角度,在规定的时间内,只让函数的第一次生效,后面的不生效,大于设定时间后,再生效。
二、使用场景:
上拉加载,滚动条,等等
三、代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function throttle(fn,delay){
var starttime=0;
return function f() {
var nowtime=Date.now();
if (nowtime-starttime>delay){
fn.call(document);
// fn.call(this);
// fn();
starttime=nowtime;
}
}
}
document.onmousemove=throttle(function () {
console.log(Math.random());
console.log(this);
},1000);
</script>
</body>
</html>
四、原理
根据上边的代码分析一下原理,其实就是设置了一个开始时间starttime和事件触发时的时间nowtime,starttime也是需要利用闭包的特性存在内存中,不被释放,通过判断nowtime-starttime是否大于我们设定的时间来决定函数的执行,这样就可以达到一个节流的效果。
注意:和防抖函数一样,节流函数也有一个this指向问题,我们需要通过call让他来指向之前的作用域下的this。