函數防抖(debounce),指觸發事件後在必定時間(好比 3 秒)內函數只能執行一次,若是這段時間(3 秒)內又觸發了事件,則會從新計算函數執行時間。app
指觸發事件後函數不會當即執行,而是在必定時間(好比 3 秒)後執行,若是這段時間(3 秒)內又觸發了事件,則會從新計算函數執行時間。函數
// 0.1.1/debounce1.page.js
/** * @desc 函數防抖-非當即執行版 * @param {Function} callback * @param {Number} wait * * @return {Function} */
const debounce = (callback, wait = 3000) => {
let timer;
return function () {
let ctx = this;
let args = arguments;
if (timer) {
clearTimeout(timer)
};
timer = setTimeout(() => {
callback.apply(ctx, args)
}, wait);
}
}
// 使用
console.log(new Date().toLocaleString());
console.log('-----');
const body = document.querySelector('body');
const btn = document.createElement('div');
btn.style = 'cursor: pointer; padding: 10px; background:red; border-radius: 5px; text-align: center; color:#fff;';
btn.innerHTML = '函數防抖非當即執行版默認 3 秒';
body.append(btn);
function callback() {
console.log(new Date().toLocaleString());
}
btn.addEventListener('click', debounce(callback));
複製代碼
指觸發事件後函數會當即執行,而後必定時間(3 秒)內不觸發事件才能繼續執行函數的效果。post
// 0.1.1/debounce2.page.js
/** * @desc 函數防抖-當即執行版 * @param {Function} callback * @param {Number} wait * * @return {Function} */
const debounce = (callback, wait = 3000) => {
let timer;
return function () {
let ctx = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
}
let callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
if (callNow) {
callback.apply(ctx, args);
}
}
}
// 使用
console.log(new Date().toLocaleString());
console.log('-----');
const body = document.querySelector('body');
const btn = document.createElement('div');
btn.style = 'cursor: pointer; padding: 10px; background:red; border-radius: 5px; text-align: center; color:#fff;';
btn.innerHTML = '函數防抖當即執行版默認 3 秒';
body.append(btn);
function callback() {
console.log(new Date().toLocaleString());
}
btn.addEventListener('click', debounce(callback));
複製代碼
// 0.1.1/debounce.page.js
/** * @desc 函數防抖-非當即執行版和當即執行版 * @param {Function} callback 回調函數 * @param {Number} wait 延遲毫秒數 * @param {Boolean} immediate true 當即執行 false 非當即執行 * * @return {Function} */
const debounce = (callback, wait = 3000, immediate = false) => {
let timer;
return function () {
let ctx = this;
let args = arguments;
if (timer) {
clearTimeout(timer)
};
if (immediate) {
let callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
if (callNow) {
callback.apply(ctx, args)
}
} else {
timer = setTimeout(() => {
callback.apply(ctx, args);
}, wait)
}
}
}
// 使用
console.log(new Date().toLocaleString());
console.log('-----');
const body = document.querySelector('body');
const btn = document.createElement('div');
btn.style = 'cursor: pointer; padding: 10px; background:red; border-radius: 5px; text-align: center; color:#fff;';
btn.innerHTML = '函數防抖非當即執行版和當即執行版默認 3 秒';
body.append(btn);
function callback() {
console.log(new Date().toLocaleString());
}
btn.addEventListener('click', debounce(callback));
複製代碼