- 你是不是遇到過提交按鈕,點擊多次發(fā)生多次提交的困惑?
- 是不是遇到過下拉搜索框每按一次鍵盤就請求一次接口,scroll、resize事件頻繁執(zhí)行的困惑?
使用 節(jié)流和防抖 就可以解決此類問題
節(jié)流
原理:初次觸發(fā)時,立即執(zhí)行事件,n秒后才能再次執(zhí)行,n秒之內(nèi)觸發(fā)無效
應(yīng)用:主要解決 按鈕重復(fù)點擊 問題
代碼實現(xiàn)
function throttle(func,time) {
let ifCanClick = true;
return function () {
if (ifCanClick) {
func.apply(this, arguments); // 執(zhí)行 并透傳this和參數(shù)
ifCanClick = false;
let setTime = setTimeout(function () {
ifCanClick = true;
clearTimeout(setTime);
}, time);
}
};
}
// 按鈕 綁定 節(jié)流
let twoDiv = document.getElementsByClassName('stop-dou')[0];
twoDiv.onclick = throttle( function (e) {
console.log('有效點擊,去執(zhí)行');
// 邏輯代碼
}, 3000);
防抖
原理:初次觸發(fā)事件,n秒后延遲執(zhí)行,沒觸發(fā)一次就重新計時
應(yīng)用:下拉搜索input框,scroll,resize,防止頁面卡頓
代碼實現(xiàn)
function debounce (func, time) {
let setTime = null
return function () {
console.log(5555)
let _this = this;
let _arguments = arguments;
clearTimeout(setTime);
setTime = setTimeout(function () {
func.apply(_this, _arguments);
}, time);
}
}
// 綁定 防抖 事件
let myInput = document.querySelector('.input-text');
myInput.onkeydown = debounce(function(e) {
console.log('開始執(zhí)行一次')
let text = e.target.value;
let showTag = document.querySelector('#showTag');
showTag.textContent = text;
}, 500)
使用 lodash.js 插件庫實現(xiàn)節(jié)流和防抖
import _ from lodash.js
_.throttle(function() { // 節(jié)流函數(shù)
// 邏輯代碼
}, 3000)
_.debounce(function() { // 防抖函數(shù)
// 邏輯代碼
}, 3000)
注意:函數(shù)參數(shù)不能用箭頭函數(shù)