防抖和节流:用于稀释事件的触发频率
一般用于input输入事件、滚动事件 稀释
- 防抖:设定一段时间执行某一个动作,如果在设定时间内,重新触发了动作,不执行,同时重置时间 debounce
- 节流:设定一段时间执行某一个动作,如果在设定时间内,重新触发了动作,不执行 throttle
<div class="box">0</div>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.box {
width: 400px;
margin: 50px;
font-size: 60px;
font-weight: 600;
color: #fff;
text-align: center;
line-height: 300px;
background-color: #9000ff;
}
</style>
公共js代码
var box = document.querySelector(".box");
var count = 0;
box.onmousemove = throttle(function (){
box.innerText = ++count;
}, 1000);
防抖
//先自增再判断,立即执行
function debounce(func, wait){
var timer = null;
return function (){
if(!timer){
func();
}else {
clearTimeout(timer);
}
timer = setTimeout(function (){
timer = null;
}, wait);
}
}
//先清除定时器,确认停止再自增,非立即执行
function debounce1(func, wait){
var timer = null;
return function (){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(function (){
func();
}, wait);
}
}
节流
//使用 Date.now(),立即执行
function throttle(func, wait){
// 声明起始时间
var startTime = Date.now();
return function (){
// 判断执行函数的事件与上次执行函数的时间间隔是否大于等待时长
if(Date.now() - startTime > wait){
func();
// 重置起始事件为当前执行函数的时间
startTime = Date.now();
}
}
}
//定时器版本,非立即执行
function throttle1(func, wait){
var timer = null;
return function (){
if(!timer){
timer = setTimeout(function (){
func();
timer = null;
}, wait);
}
}
}