防抖:事件在n秒内执行一次,若再次触发则重新计算时间,常用在input即时搜索。
节流:事件在n秒内只执行一次,不管怎么再次触发,也只执行一次,常用在点击按钮。
let content = document.getElementById('content');
function count() {
content.innerHTML = num++;
}
防抖
- 事件触发后1秒再执行(延迟执行)
function debounce(func, wait) {
let time;
return function () {
if (time) {//如果有定时器,清除
clearTimeout(time);
}
time = setTimeout(() => {//没有定时器增加一个,1秒后执行函数
func();
}, wait);
}
}
content.onmousemove = debounce(count, 1000);
- 事件触发后,立即执行,1秒后才能再次执行(立即执行)
function debounce(func, wait) {
let time;
return function () {
if (time) {
clearTimeout(time) //取消之前任务
}
let flag = !time; //用来标记time状态
time = setTimeout(() => { //增加一个定时器
func()
time = null; //1秒后清空定时器
}, wait);
if (flag) { //第一次执行
func();
}
}
}
content.onmousemove = debounce(count, 1000);
节流
- 固定时间去发送请求
function throttle(func, wait) {
let time;
return function () {
if (!time) { //是否有定时器
time = setTimeout(() => {
time = null; //2秒后清空定时器
func(); //执行函数
}, wait);
}
}
}
content.onmousemove= throttle(count, 2000);
- 时间戳
function throttle(func, wait) {
let prev = 0; //之前的时间
return function () {
let now = Date.now() //现在的时间
if (now - prev > wait) { //现在时间减去之前时间
func();
prev = now; //重新赋值
}
}
}
content.onmousemove= throttle(count, 2000);