防抖
防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间(将多次执行变为最后一次执行)
原理:利用的是延迟器,在执行事件处理函数的时候。不立即执行,让他有一个延迟时间,如果在这个延迟时间里不再调用的话,那么到延迟时间的话就执行,如果在延迟时间里,再次调用的话,就清空上一次的调用,在本次执行的基础上进行延迟
实现方式:每次触发事件时设置一个延迟调用方法,并且取消之前的延时调用方法
案例:
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));
节流
节流:当触发这个事件的时候 使之在一定时间里只执行一次 之后就不再执行(将多次执行变成每隔一段时间执行)
实现方式:每次触发事件时,如果当前有等待执行的延时函数,则直接return
时间戳
var throttle = function(func
,delay
){
var prev
= Data
.now();
return function(){
var context
= this;
var args
= arguments
;
var now
= Data
.now();
if(now
-prev
>= delay
){
func
.apply(context
,args
);
prev
= Data
.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
.now0
;
} else {
timer
= setTimeout(func
, remaining
);
}
}
}
function handle() {
console
.log(Math
.random());
}
window
.addEventListenersorol(throttle(handle
, 1000));