防抖
就是指触发事件后在n秒内函数只能执行一次,如果在n秒内又触发了事件,则会重新计算函数执行时间。
var box = document.querySelector('.box');
var testDebounce = debounce(move, 1000);
box.onmousemove = testDebounce;
function move(ev) {
console.log(ev, this);
this.innerHTML = ev.clientX;
}
function debounce(fn, wait) {
let timmer = null;
return function () {
var args = arguments;
timmer && clearTimeout(timmer);
timmer = setTimeout(() => {
fn.apply(this, args);
}, wait);
}
}
节流
就是指连续触发事件但是在一段时间中只执行一次函数。
var box = document.querySelector('.box');
var testjl = jl(move, 400);
box.onmousemove = testjl;
function move(ev) {
this.innerHTML = ev.clientX;
}
// function jl(fn, wait) {
// let timmer = null;
// return function () {
// var args = arguments;
// if (!timmer) {
// timmer = setTimeout(() => {
// timmer = null;
// fn.apply(this, args);
// })
// }
// }
// }
function jl(fn, wait) {
let last = 0;
return function () {
var args = arguments;
var now = Date.now();
if (now - last > wait) {
fn.apply(this, args);
last = now;
}
}
}