这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战
作为JS的基础,防抖节流应该是经典的不能再经典的了
一、防抖函数
1、定义
其实为什么叫防抖函数呢,讲白话就是防止抖动。也就是当持续频繁的触发事件的时候,会影响性能。为了优化这种频繁触发事件的情况,出现了防抖函数。
2、使用场景
比如说:window的resize,scroll,mousedown、mousemove,keyup、keydown...
3、具体实现
首先我们要知道实现防抖的原理是: 不管怎么触发事件,要执行的东西一定在事件触发n秒之后才执行。
也就是说:如果在事件触发的n秒内又触发了,就以新的时间为准,n秒之后才执行。
function debounce(fn, delay) {
let timer;
return function() {
var context = this; // this指向
var args = arguments; // event对象
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(context, args)
}, delay);
}
}
至此,我们就实现了一个简单的防抖函数。
4、测试
然后我们来测试一下刚写的防抖函数:
<input type="text" id="input">
function inputFun(value) {
console.log('你输出的结果是' + value)
}
const input = document.getElementById("input")
const debounceInput = debounce(inputFun, 500)
// 监听Input框的输入
input.addEventListener('keyup', function(e) {
debounceInput(e.target.value)
})
二、节流函数
1、定义
节流函数就是一段时间只做一件事情,能够实现性能较好的懒加载。
2、使用场景
比如监听滚动条和顶部的距离。
3、具体实现
前面也说到,节流就是一段时间只做一件事情,那么只需要给一个变量,判断是否完成了这个事情。
function throttle(func, wait) {
let timerOut;
return function() {
let context = this;
let args = arguments;
if (!timerOut) {
timerOut = setTimeout(function() {
timerOut = null
func.apply(context, args)
}, wait)
}
}
}
4、测试
同样的我们来测试一下,比如我们需要监听浏览器滚动事件,返回当前滚动条与顶部的距离。
那么我们可以通过节流函数:
function showTop() {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置' + scrollTop)
}
window.onscroll = throttle(showTop, 1000)