函数节流
概念:在规定的时间段内(例如1000ms),即使事件触发了很多次,都只执行一次对应的任务。
栗子:在我们进入地铁站时通过闸机,每隔3秒内只允许一个人通过,即使多个人同时刷卡,也只允许一个人通过。
运用场景:如果我们在改变浏览器的大小或者监听鼠标移动事件等事件(短时间内触发多次),为了节省浏览器性能开销,就可以使函数节流来优化。
代码实现:
(function(){
let ele = document.getElementById("jieliu")
let count = 0
let don = true
ele.addEventListener('mousemove',e => {
count++
if(!don){
return
}
don = false
let timer = setTimeout(()=>{
console.log(count)
don = true
},1000)
})
})();
函数防抖
概念:一个事情连续触发,只执行最后一次触发后对应的任务。
栗子:当我们进入地铁车厢里的时候,要等所有的人都上车后,再关门。
运用场景:一段连续触发的事件,只想让函数触发一次
代码实现:
(function(){
let ele = document.getElementById("fangdou")
let count = 0
let don = true
let timer = null
ele.addEventListener('mousemove',e => {
clearTimeout(timer)
timer = setTimeout(()=>{
count++
console.log(count)
don = true
},1000)
})
})()
完整代码:
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="jieliu" style="width:200px;height:200px;background-color:red">jieliu</div>
<div id="fangdou" style="width:200px;height:200px;background-color:red">fangdou</div>
</body>
<script src="../src/jieliu.js"></script>
</html>
//jieliu.js
(function(){
let ele = document.getElementById("jieliu")
let count = 0
let don = true
ele.addEventListener('mousemove',e => {
count++
if(!don){
return
}
don = false
let timer = setTimeout(()=>{
console.log(count)
don = true
},1000)
})
})();
(function(){
let ele = document.getElementById("fangdou")
let count = 0
let don = true
let timer = null
ele.addEventListener('mousemove',e => {
clearTimeout(timer)
timer = setTimeout(()=>{
count++
console.log(count)
don = true
},1000)
})
})()