理解
- 防抖是将多次执行变为只执行一次,节流是将多次执行变为每隔一段时间执行
参考
源码
防抖
function debounce(func, delay) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
function debounce(fn, wait) {
var timeout = null;
if(timeout !== null) {
console.log('清除定时器啦')
clearTimeout(timeout);
}
timeout = setTimeout(fn, wait);
}
}
function debounce(fn, wait){
let timer;
return function(){
if(timer){
clearTimeout(timer); }
timer = setTimeout(()=>{
fn.apply(this, arguments);
clearTimeout(timer);
timer = null;
},wait);
}
}
节流
function throttle(func, delay) {
let wait = false
return (...args) => {
if (wait) {
return
}
func(...args)
wait = true
setTimeout(() => {
wait = false
}, delay)
}
}
var throttle = function(func, delay) {
var timer = null
var prev = Date.now()
return function() {
var context = this
var args = arguments
var now = Date.now()
var remain = delay - (now - prev)
clearTimeout(timer)
// 如果剩余时间小于0,就立刻执行
if (remain <= 0) {
func.apply(context, args)
prev = Date.now()
} else {
timer = setTimeout(func, remain)
}
}
}
function throttle (fn, wait) {
let timer
let context, args
return function () {
context = this
args = arguments
// 如果不存在 timer 表示当前不在周期内
if (!timer) {
// 开始一个新周期
timer = setTimeout(() => {
fn.apply(context, args)
// 周期结束
clearTimeout(timer)
timer = null
}, wait)
}
}
}