防抖节流
防抖和节流是对应的:
防抖是规定时间内触发就一直延迟,直到规定时间内不触发了就执行最后一次事件;
节流是执行第一次,在规定时间内不会再次触发,过了规定时间就会再次触发的。
防抖代码:
function debounce(fn, wait) {
var timeout = null;//每次执行函数的时候如果上次没有执行完成就重新赋值
return function() {
if(timeout !== null)
clearTimeout(timeout);//如果之前有定时器的话就清除定时器
timeout = setTimeout(fn, wait);//每次触发都重新执行定时器
}
}
// 处理函数
function handle() {
console.log(Math.random());
}
// 滚动事件
window.addEventListener('scroll', debounce(handle, 1000));
节流代码:
时间戳方案
var throttle = function(func, delay) {
var prev = Date.now();
return function() {
var context = this;
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
func.apply(context, args);
prev = Date.now();
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
定时器方案
var throttle = function(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
时间戳+定时器
var throttle = function(func, delay) {
var timer = null;
var startTime = Date.now();
return function() {
var curTime = Date.now();
var remaining = delay - (curTime - startTime);
var context = this;
var args = arguments;
clearTimeout(timer);
if (remaining <= 0) {
func.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(func, remaining);
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));