之前对防抖、节流这两个概念一直很混淆,实际上已在很多场景使用,但并不清楚这样做的目标是什么,好在哪里?突然在一次讨论中被八股文了,才意识到自己应该是时候关注一下了,于是就动手操刀一把,抓住真凶!因为知其然也要知其所以然嘛!
防抖:在指定时间内连续触发一个函数,结束后最终只执行一次。使用场景:改变浏览器窗口大小(onresize)或者滚动条位置(onscroll)触发事件。
<input id="antiShakeBtn" type="text" value="" placeholder="防抖测试">
// 防抖
function antiShakeHandle (callback, delay) {
var timer = antiShakeHandle.timer;
var clearTimer = function () {
clearInterval(timer);
timer = undefined;
};
return function () {
clearTimer();
timer = setTimeout(function () {
if (Object.prototype.toString.call(callback) === '[object Function]') callback();
}, delay || 200);
}
}
document.getElementById('antiShakeBtn').oninput = antiShakeHandle(function () {
console.log('防抖成功');
}, 1000);节流:持续触发一个函数,最终在每个时间周期内间隔执行一次,起到了稀疏频次的作用。使用场景:高频次点击搜索触发接口请求,以防止暴力点击行为。
<input id="throttleBtn" type="button" value="节流">
// 节流
function throttleHandle (callback, delay) {
var timer = throttleHandle.timer;
var clearTimer = function () {
clearInterval(timer);
timer = undefined;
};
return function () {
if (timer) return;
timer = setInterval(function () {
if (Object.prototype.toString.call(callback) === '[object Function]') callback();
clearTimer();
}, delay || 200);
}
}
document.getElementById('throttleBtn').onclick = throttleHandle(function () {
console.log('节流成功');
}, 1000);
发表评论