目录
节流(throttle
):不管事件触发频率多高,只在单位时间内执行一次。
既该事件不会重复触发,与防抖最大的区别,单位时间内触发就取消,防抖是以后一个为准
有两种方式可以实现节流,使用时间戳和定时器。
时间戳实现
第一次事件肯定触发,最后一次不会触发
function throttle(event, time) {
let pre = 0;
return function (...args) {
if (Date.now() - pre > time) {
pre = Date.now();
event.apply(this, args);
}
}
定时器实现
第一次事件不会触发,最后一次一定触发
function throttle(event, time) {
let timer = null;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
timer = null;
event.apply(this, args);
}, time);
}
}
}
结合版
定时器和时间戳的结合版,也相当于节流和防抖的结合版,第一次和最后一次都会触发
function throttle(event, time) {
let pre = 0;
let timer = null;
return function (...args) {
if (Date.now() - pre > time) {
clearTimeout(timer);
timer = null;
pre = Date.now();
event.apply(this, args);
} else if (!timer) {
timer = setTimeout(() => {
event.apply(this, args);
}, time);
}
}
}
应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>throttle</title>
</head>
<body>
<script>
function coloring(){
let r=Math.floor(Math.random()*255);
let g=Math.floor(Math.random()*255);
let b=Math.floor(Math.random()*255);
document.body.style.background=`rgb(${r},${g},${b})`
}
//定时器版
function throttle(fn, delay) {
let timer
return function (...args) {
if(!timer){
timer=setTimeout(()=>{
timer=null
fn.apply(this, args)
}, delay)
}
}
}
//时间戳版
function throttle2(fn,delay){
let pre=0
return function(...args){
if(Date.now()-pre > delay){
timer=setTimeout(()=>{
pre=Date.now()
fn.apply(this, args)
})
}
}
}
window.addEventListener("resize",throttle2(coloring,1000))
</script>
</body>
</html>