防抖和节流
防抖 (debounce)
同一个事件高频触发,n秒内所有事件只触发最后一次,例如输入框请求API
// 防抖debounce代码:
function debounce(fn) {
let timeout = null; // 创建一个标记用来存放定时器的返回值
return function (arguments) {
// 每当用户输入的时候把前一个 setTimeout clear 掉
clearTimeout(timeout);
// 然后又创建一个新的 setTimeout,
//这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, 500);
};
} // 处理函数
// --------------------
// 立即执行
const debounce1 = function(fn, wait){
let timer
return function(...args){
let immdete = !timer
let that = this
if(timer) clearTimeout(timer)
timer = setTimeout(function(){
timer = null
},wait)
if(immdete) fn.apply(that, args)
}
}
节流(throttle)
水流滴答来形容~~
n秒内高频触发事件只执行一次,例如页面滚动事件
// 定时器
function throttle(fn, interval) {
var timer,
__self = fn,
firstInter = true;
return function () {
var args = arguments,
_that = this;
if (firstInter) {
// 第一次执行无需延迟
__self.apply(_that, args);
firstInter = false;
}
if (timer) return
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
__self.apply(_that, args);
}, interval || 500);
};
}
// ---------------
// 时间戳
const throttle1 = function(fn, wait){
let timer = 0
return function(){
let now = Date.now()
if(now - timer>= wait){
timer = now
fn.apply(this, arguments)
}
}
}