节流
一定的时间内函数只执行一次。(每隔一定时间可以执行某个函数)
如mousemove事件只要鼠标在元素里面移动就会触发,事件执行次数多少用户肉眼是不容易察觉。
var canMove = true; // 创建变量控制函数是否执行
document.querySelector(".box1").onmousemove=function(){
// 每次执行函数判断变量是否为true,true则可以执行函数的逻辑代码
if(canMove){
console.log(1)
// 把变量设置为false
canMove=false
setTimeout(function(){
canMove=true
}, 500);
}
}
防抖
函数频繁触发的情况下,只有足够的空闲时间,才执行代码一次(某个操作结束后才执行函数)
如:窗口滚动条滚动触发的事件,由于滚动事件一般是滚动停止后才执行函数,可以选择函数防抖
var setIndex = ""; // 创建变量记录定时器的索引号
window.onscroll=function(e){
clearTimeout(setIndex)
setIndex=setTimeout(function(){
console.log("scroll")
},500)
}
requestAnimationFrame
如果用定时器做动画,由于每次都会触发重构和重绘,有时会有卡顿现象。
requestAnimationFrame 是html5增加的一个动画api。间隔时间是 1000/60(电脑屏幕刷新率)是固定的。
var div = document.querySelector(".box1")
var num=0;
function animate(){
num+=10
div.style.left=num+"px"
if(num<500){
window.requestAnimationFrame(animate)
}
}
animate()