这个优化计划是参照 【前端机能】高机能转动 scroll 及页面衬着优化
在这里简朴的把两个体式格局写出来,以便疾速相识。。
第一种:防抖(也就是转动完毕才实行)
演示:
闭包:
/*
延时实行
@param fn function
@param wait number
@return function
*/
function debounce(fn, wait) {
var timeout = null;
return function() {
if(timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn, wait);
}
}
// 处置惩罚函数
function handle() {
console.log(Math.random());
}
// 转动事宜
window.addEventListener('scroll', debounce(handle, 500));
直接写:
var timeout = null;
window.addEventListener('scroll', function() {
if(timeout !== null) clearTimeout(timeout);
timeout = setTimeout(function() {
var scrollTop = this.scrollY;
console.log(scrollTop);
}.bind(this), 500);
});
第二个是撙节(Throttling)转动的过程当中距离实行,比方转动加载图片结果,不可能比及转动完毕才实行加载函数数吧,所以这里能够做一个距离实行。。
演示:
闭包:
/*
撙节函数
@param fn function
@param wait number
@param maxTimeLong number
@return function
*/
function throttling(fn, wait, maxTimelong) {
var timeout = null,
startTime = Date.parse(new Date);
return function() {
if(timeout !== null) clearTimeout(timeout);
var curTime = Date.parse(new Date);
if(curTime-startTime>=maxTimelong) {
fn();
startTime = curTime;
} else {
timeout = setTimeout(fn, wait);
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttling(handle, 300, 1000));
直接写:
var timeout = null,
startTime = Date.parse(new Date); // 最先时候
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', function() {
if(timeout !== null) clearTimeout(timeout);
var curTime = Date.parse(new Date); // 当前时候
if(curTime-startTime>=1000) { // 时候差>=1秒直接实行
handle();
startTime = curTime;
} else { // 不然延时实行,像转动了一下,差值<1秒的那种也要实行
timeout = setTimeout(handle, 300);
}
});
诸如此类事宜的另有resize事宜都能够运用这两种体式格局,固然运用哪种,还要看项目需求了。。感谢关注~