节流
这是一个没有做节流的改变屏幕尺寸可以变色的效果,会进行反复加载
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></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})`
}
window.addEventListener('resize',coloring)
</script>
</body>
</html>
下面演示添加节流方法1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></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(func,delay){
let timer;
return function(){
let context = this;
let args = arguments;
if(timer){
return;
}
timer = setTimeout(function(){
func.apply(context,args)
timer = null
},delay)
}
}
window.addEventListener('resize',throttle(coloring,1000))
</script>
</body>
</html>
下面演示添加节流方法2:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></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(func,delay){
let pre = 0;
return function(){
let now = new Date();
let context = this;
let args = arguments;
if(now - pre > delay){
func.apply(context,args)
pre = now
}
}
}
window.addEventListener('resize',throttle(coloring,1000))
</script>
</body>
</html>
防抖