防抖:在连续触发事件时,只会执行一次
节流:在一定时间内只会被触发一次
共同点:都能阻止事件的高频触发
HTML与CSS部分
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#content {
width: 100%;
height: 200px;
background-color: gray;
opacity: 0.4;
text-align: center;
line-height: 200px;
font-size: 40px;
}
#content1 {
width: 100%;
height: 200px;
background-color: gray;
opacity: 0.4;
text-align: center;
line-height: 200px;
font-size: 40px;
margin-top: 20px;
}
#content2 {
width: 100%;
height: 200px;
background-color: gray;
opacity: 0.4;
text-align: center;
line-height: 200px;
font-size: 40px;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="content"></div>
<div id="content1"></div>
<div id="content2"></div>
</body>
JS部分
//防抖
var content = document.querySelector("#content");
// console.log(content);
var num = 1;
var times;
content.onmousemove = function(){
let obj = times;
// console.log(obj);
clearTimeout(times);
times = setTimeout(()=>{
times = null;
},500)
if(!obj){
content.innerHTML = num++;
}
}
//节流
//1.延时器
var content1 = document.querySelector("#content1");
var sum = 1;
var time;
content1.onmousemove = function(){
if(!time){
time = setTimeout(()=>{
time = null;
content1.innerHTML = sum++;
},1000)
}
}
//2.时间戳
var content2 = document.querySelector("#content2");
var num1 = 1;
var timeNew = 0;
content2.onmousemove = function(){
var timeOld = Date.now();
if(timeOld-timeNew > 1000){
timeNew = timeOld;
content2.innerHTML = num1++;
}
}
防抖
节流