一、防抖
<input placeholder="请输入电话"<script>
// 防抖 =>将多次操作变成一次
let telInput =document.querySelector('input')
telInput.addEventListener('input', antiShake(demo, 2000))
//防抖封装
function antiShake(fn,wait){
let timeOut = null;
return args => {
if(timeOut)clearTimeout(timeOut)
timeOut= setTimeout(fn,wait);
}
}
function demo(){
console.log('发起请求')}
}
二、节流
// 节流 =>一定时间内只调用一次函数
// 应用场景 =>1.提交表单 2.高频监听事件 let box = document.querySelector(“.box”)
let box =document.querySelector('.box')
box.addEventListener("touchmove", throttle(demo,2080))
function throttle(event, time){
let timer = null
return function() {
if(!timer){
timer = setTimeout(()=>{
event();
timer = null;
},time);
}
}
}
/**
* 防抖
* @param fn 执行函数
* @param ms 间隔毫秒数
*/
export const debounce = (fn: Function, ms: number) => {
return (...args: any[]) => {
if (window.lazy !== null) {
clearTimeout(window.lazy)
}
window.lazy = setTimeout(() => {
fn(...args)
}, ms)
}
}
/**
* 节流
* @param fn 执行函数
* @param ms 间隔毫秒数
*/
export const throttle = (fn: Function, ms: number): Function => {
let last = 0
return function(...args: any[]) {
const now = Date.now()
if (now - last > ms) {
fn(...args)
last = now
}
}
}