两者对比
debounce
const debounce = (fn, wait) => {
var timerId = null;
return function () {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
};throttle
最后更新于
const debounce = (fn, wait) => {
var timerId = null;
return function () {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
};最后更新于
const throttle = (fn, wait) => {
var wait = wait || 0;
var lastTime = 0;
return function () {
var currentTime = +new Date();
if (currentTime > lastTime + wait) {
lastTime = currentTime;
fn.apply(this, arguments);
}
};
};function debounce(fn, wait) {
// 先说下是干啥的 防抖
var timerId = null;
// 电梯举例: 加入你坐电梯,你设置时间,在这个时间段内,只要有人按 你就会暂停。这个过程可能需要等待几分钟,最终没人进电梯了
return function () {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
}function throttle(fn, wait) {
// 节流代表的意思是 你是个很没有耐心的人 throttle
// 这个时间段内 执行多少次 你不管 ,只要超过了 这个时间 你就会走
var lastTime = 0;
return function () {
currentTime = +new Date();
if (currentTime > lastTime + wait) {
lastTime = currentTime;
fn.apply(this, arguments);
}
};
}function debounce(fn, wait) {
let timerId = null;
return function () {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
}function throttle(fn, wait) {
var waite = wait || 0;
var lastTime = 0;
return function () {
var currentTime = +new Date();
if (currentTime > lastTime + waite) {
lastTime = currentTime;
fn.apply(this, arguments);
}
};
}//去抖动
const debounce = (fn, wait) => {
var timerId = null;
return function () {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
};// 节流
const throttle = (fn, wait) => {
var lastTime,
wait = wait || 0;
return function () {
var currentTime = +new Date();
if (currentTime - lastTime > wait) {
lastTime = currentTime;
fn.apply(this, arguments);
}
};
};