防抖
使用场景 (事件多次触发只执行最后一次)
- 登录、发短信等按钮避免用户点击太快,以致于发送了多次请求,需要防抖
- 调整浏览器窗口大小时,resize 次数过于频繁,造成计算过多,此时需要一次到位,就用到了防抖
- 文本编辑器实时保存,当无任何更改操作一秒后进行保存
<input type="text" id="input" placeholder="请输入内容" />
<script>
function debounce(callback, delay) {
if (typeof callback !== 'function') {
throw new TypeError('callback is not a function');
}
let timer;
return function () {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
callback.call(this);
}, delay);
};
}
let input = document.getElementById("input");
input.oninput = debounce(function () {
console.log(this.value);
}, 1000);
function debounce(fun, delay) {
return function (...args) {
clearTimeout(fun.id);
fun.id = setTimeout(() => {
fun.call(this, ...args);
}, delay);
};
}
let inputb = document.getElementById("debounce");
let debounceAjax = debounce((content, arg, obj) => {
console.log(" content ", content);
console.log(" arg ", arg);
console.log(" obj ", obj);
}, 1000);
inputb.addEventListener("keyup", function (e) {
debounceAjax(e.target.value, { x: 5, y: 10 }, { z: 5, k: 10 });
});
节流
使用场景 (事件多次触发减少执行次数)
- scroll 事件,每隔一秒计算一次位置信息等
- 浏览器播放事件,每个一秒计算一次进度信息等
let input = document.getElementById("input");
function throttle(callback, delay) {
let flag = true;
return function () {
if (flag) {
setTimeout(() => {
callback.call(this);
flag = true;
}, delay);
}
flag = false;
};
}
input.oninput = throttle(function () {
console.log(this.value);
}, 1000);
window.onscroll = throttle(function () {
console.log("hello");
}, 1000);