在性能优化实践中,遇到scroll事件,优先须要考虑节流。 节流函数顾名思义,就是要使密集频繁触发的函数,按照有规律有节制的过程去执行,那么背后的原理是什么?一步步实现吧。性能优化
var num = 0
window.onscroll = function () {
console.log('回调函数执行' + (++num) + '次')
}
复制代码
var num = 0
var timer = null
var cb = function(){
console.log('回调函数执行' + (++num) + '次')
}
window.onscroll = function () {
clearTimeout(timer)
timer = setTimeout(() => {
cb()
}, 1000)
}
复制代码
var num = 0
var cb = function(){
console.log('回调函数执行' + (++num) + '次')
}
var throttle = function (fn, delay) {
var timer = null
return function () {
clearTimeout(timer);
timer = setTimeout(function() {
fn();
}, delay);
}
}
window.onscroll = throttle(cb, 1000)
复制代码
var num = 0
var cb = function(){
console.log('回调函数执行' + (++num) + '次')
}
var throttle = function (fn, delay, atleast) {
// 声明定时器
var timer = null
var previous = null
return function () {
// 每次页面滚动时候都会生成新的时间戳
var now = +new Date()
// 若是是第一次滚动
if ( !previous ) previous = now
// 不断的滚动,直到时间间隔知足条件,执行回调函数,更新previous,清空定时器
if ( atleast && now - previous > atleast ) {
fn();
previous = now
clearTimeout(timer)
// 不知足时间间隔条件,仍是进函数中先清空上次的定时器
// 并生成新的定时器,
} else {
clearTimeout(timer)
timer = setTimeout(function() {
fn()
}, delay);
}
}
}
window.onscroll = throttle(cb, 1000, 400)
复制代码