一.防抖
一个方法请求多次,但 只执行最后一次
var inp = document.querySelector('input')
inp.oninput = debounce(function () {
console.log(this.value);
}, 500)
function debounce(fn, time) {
let t = null
return function () {
if (t !== null) {
clearTimeout(t)
}
t = setTimeout(() => {
fn.call(this)
}, time);
}
}
二.节流
多次请求,但要控制 请求的次数
window.onscroll = throttle(function () {
console.log("object");
}, 1000)
function throttle(fn, delay) {
let flag = true
return function () {
if (flag) {
setTimeout(() => {
fn.call(this)
flag = false
}, delay)
}
flag = true
}
}