Skip to main content

JS | 防抖节流

函数节流(throttle)

限制一个函数在一定时间内只能执行一次。 规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

////////[节流:限制一个函数在一定时间内只执行一次,如果在该时间内多次触发也不会执行]///////////////
// 节流-时间戳版
function throttle(cb, await) {
// let preTime = 0;
let preTime = Date.now();
return function () {
const nowTime = Date.now();
if (nowTime - preTime >= await) {
preTime = nowTime;
return cb.apply(this, arguments);
}
};
}

// 节流-settimeout
function throttle(cb, await) {
let timer = null;
return function () {
if (timer === null) {
timer = setTimeout(() => {
cb.apply(this, arguments);
timer = null;
}, await);
}
};
}

应用场景

  • 按钮事件
  • 滚动事件

函数防抖(debounce)

函数防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。 简单的说,当一个动作连续触发,则只执行最后一次。

在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。 通俗点说 就是当你的事件触发后 n 秒没有再次触发,就执行。如果 n 秒内你又触发了。那就从该触发时间开始计算

function debounce(fun, delay) {
return function (args) {
let that = this;
let _args = args;
clearTimeout(fun.id);
fun.id = setTimeout(function () {
fun.call(that, _args);
}, delay);
};
}

function debounce(fn, interval = 300) {
let timeout = null;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, interval);
};
}

应用场景

  • 搜索输入