封装防抖节流函数
防抖
// 防抖函数
function debounce(fn,delay) {
let timer = null;
return ()=>{
// 清楚上一次的计时器
clearTimeout(timer)
timer = setTimeout(()=>{
// 改变this指向
fn.apply(this)
},delay)
}
}
//测试 在html搞一个id为box的盒子元素
document.getElementById('box').onclick = debounce(()=>{
console.log('点击事件'+Date.now())
},1000)
防抖2
//防抖
// 输入完毕后过2秒再查询(延迟执行)
function debounce(fn, wait) {
let timer = null;
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, wait)
}
}
//防抖
// 输入完毕后立即执行查询,过2秒才能进行查询(立即执行)
function debounce(fn, wait) {
let timer = null;
return function(){
if (timer) clearTimeout(timer);
let callnow = !timer; //类型转换
timer = setTimeout(()=>{
timer = null;//清空当前定时器
},wait)
if(callnow) fn.apply(this);//第一次执行
}
}
let btn = document.getElementById("btn");
// 点击之后过两秒之后再触发,连续多次点击不会触发
btn.onclick = debounce(()=>{
console.log(1)
},2000)
// 点击事件立即触发,连续点击不会触发,2秒之后点击再次触发
// btn.onclick = debounce1(() => {
// console.log(1)
// }, 2000)
节流
// 节流函数
function throttle(fn,delay){
let timer = 0;
return ()=>{
let nowtime = Date.now(); //注意当前事件一定得写在return函数内
if(nowtime - timer > delay){
fn.call(this);
// 同步时间
timer = nowtime
}
}
}
//测试 高度大一点 出现滚动条 测试
window.onscroll = throttle(function() {
console.log(Date.now())
},1000)
节流2
// 节流 点击之后过两秒之后才会触发事件
function throule(fn,wait){
let timer;
return function (){
if(!timer){
timer = setTimeout(()=>{
timer = null;
fn.apply(this)
},wait)
}
}
}
let btn = document.getElementById("btn");
// 每隔两秒触发一次 再此期间点击多少次都不会出发啊
btn.onclick = throule(()=>{
console.log( new Date())
},2000)
异步使用防抖语法
click: utils.debounce(async (row)=>{
//里面写操作
},2000)