防抖
所谓防抖就是在事件触发后通过定时器在规定时间后去执行代码,期间如果继续触发事件定时器将会进行重置,例如浏览器搜索,当你停止输入一定时间后比如0.5s浏览器会自动搜索。
function debounce (func, delay) {
// 利用闭包保存定时器
let timer;
return function () {
let context = this;
let arg = arguments;
// 在规定时间内再次触发会先清除定时器后再重设定时器
clearTimeout(timer)
timer = setTimeout(function () {
func.apply(context, arg)
}, delay)
}
}
节流
所谓节流,就是指连续触发事件但是在 n秒 中只执行一次函数,常见例子页面滚动、窗口调整大小和登录表单的发送。
有两种方法,分别是时间戳和定时器。具体如下代码
时间戳版
function throttle(func, limit) {
let prea = 0;
return function () {
const args = arguments;
const context = this;
const timer = Date.now();//获取当前时间
//时间差不能小于规定时间
if (timer - prea >= limit) {
func.apply(context,args);
prea = timer
}
};
}
定时器版
function throttle(func, limit) {
let timeSwitch = true; // 开关
return function () {
const args = arguments;
const context = this;
//开关只有在打开状态下才能执行代码
if (timeSwitch) {
func.apply(context, args);
timeSwitch = false;
setTimeout(() => {
// 定时器用来进行保证在一定时间内开关的状态
timeSwitch = true;
}, limit);
}
};
}