防抖函数
let timer
clearTimeout(timer)
timer = setTimeout(function(){
},delay)
实际的应用
使用echarts
时,改变浏览器宽度的时候,希望重新渲染
echarts
的图像,可以使用此函数,提升性能。(虽然echarts
里有自带的resize
函数)
典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时,解决搜索的bug
// 防抖的函数
function debounce(callback,delay){
let timer
return function(arg){
clearTimeout(timer)
timer = setTimeout(() => {
callback(arg)
}, delay);
}
}
function func(value){
console.log(value)
}
var input = document.getElementById('input');
var debounceFn = debounce(func,2000)
input.addEventListener('keyup',function(e){
debounceFn(e.target.value)
})
节流函数
当持续触发事件的时候,保证一段时间内,只调用一次事件处理函数
一段时间内,只做一件事情
实际应用 表单的提交
典型的案例:鼠标不断点击触发,规定在n秒内多次点击只有一次生效
function throttle(func,wait){
let timeOut
return function(){
if(!timeOut){
timeOut = setTimeout(() => {
func()
timeOut = null;
}, wait);
}
}
}
function handle(){
console.log(Math.random())
}
document.getElementById('button').onclick = throttle(handle,2000)
防抖节流在图片懒加载中的运用
let num = document.getElementsByTagName('img').length;
let img = document.getElementsByTagName('img');
let n = 0; // 存储图片加载到的位置,避免每次都从第一张图片开始遍历
let isLoading = false; // 是否当前容器/页面的图片加载完成
let _clientHeight = document.documentElement.clientHeight; // 可见区域高度
let _scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
// 监听窗口变化重新计算可视区域
function computedClientHeight(){
_clientHeight = document.documentElement.clientHeight; // 可见区域高度
}
// 页面载入完毕加载可视区域内的图片
lazyLoad();
function lazyLoad(){
// 获取滚动条距离顶部高度
isLoading = n >= num;
_scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
for(let i = n;i<num;i++){
if(img[i].offsetTop<_clientHeight+_scrollTop){
if(img[i].getAttribute('src')==''){
img[i].src = img[i].getAttribute('data-src')
}
n = i + 1
}
}
}
function throttle(func,wait,flag){
let timeOut;
return function(){
if(flag) return;
if(!timeOut){
timeOut = setTimeout(() => {
timeOut = null;
func()
}, wait);
}
}
}
function debounce(callback,delay){
let timer;
return function(arg){
clearTimeout(timer);
timer = setTimeout(() => {
callback(arg)
}, delay);
}
}
// 使用了节流函数~实现性能较好的懒加载
window.addEventListener('scroll',throttle(lazyLoad,100,isLoading))
// 使用了防抖函数~优化不断触发的窗口变化
window.addEventListener('resize',debounce(computedClientHeight,800))