什么是节流函数?节流函数既是某个函数只能在某个时间段内只能执行一次,我们在开发中如果使用了类似scroll,onsize,mouse事件,都会非常频繁的监听这个函数,如果在这函数里面操纵dom,代价将是非常大的,笔者遇到的一个项目问题正是如此,通过websocket推送端,在scroll过程中发送即时消息给接收端,接收端在收到消息之后进行页面dom操作,因为用了一些页面大小位置监听元素,所以指示页面极度卡顿,后面想到稀释发送次数来缓解接收端的压力,也就是我今天讲的主角,节流函数
1 通过定时器实现,
// 定时器方案,
function throttle(fn,delay){
var timer = null;
return function(){
var context = this;
var args = arguments;
if(!timer){
timer = setTimeout(function(){
fn.apply(context,args);
timer = null;
},delay)
}
}
}
function handle(){
console.log("我要干点什么呢")
}
window.addEventListener("scroll",throttle(handle,50));
2 利用时间戳差进行节流// 时间戳方案
function throttle(fn,wait){
var pre = Date.now();
return function(){
var context = this;
var args = arguments;
var now = Date.now();
if( now - pre >= wait){
fn.apply(context,args);
pre = Date.now();
}
}
}
function handle(){
console.log("我要干点什么呢")
}
window.addEventListener("scroll",throttle(handle,50));
3 利用一些触发特性的元素计算,如监听scroll,可以每次滚动多少px触发handle函数,道理同上时间戳差类似