防抖和节流
防抖:重复触发不执行,不触发的一段时间后执行(lol回城机制)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
#box {
width: 600px;
height: 300px;
background-color: pink;
margin: 0 auto;
}
</style>
<body>
<div id="box"></div>
</body>
<!-- 引入后缀是lodash.min.js的文件,不要引入后缀是lodash.core.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script>
//鼠标在盒子内的x坐标 = 鼠标距离文本窗口的距离 - 当前盒子左上角为原点定位x轴坐标
// document.querySelector('#box').onmousemove = function (e) {
// let left = e.pageX - this.offsetLeft
// let top = e.pageY - this.offsetTop
// this.innerHTML = `x:${left},y:${top}`
// }
// const debounce = (fn, time) => {
// let timer = null
// return function (...args) {
// clearTimeout(timer)
// timer = setTimeout(() => {
// fn.apply(this, args)
// }, time)
// }
// }
document.querySelector('#box').onmousemove = _.debounce(function (e) {
let left = e.pageX - this.offsetLeft
let top = e.pageY - this.offsetTop
this.innerHTML = `x:${left},y:${top}`
}, 1000)
</script>
</html>
节流:持续触发也执行,只不过执行的频率变低了(射击游戏)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 600px;
height: 300px;
background-color: pink;
margin: 0 auto;
}
</style>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<div id="oDiv"></div>
<script>
// 节流:持续触发也执行,只不过触发的频率变低了。
/* const throttle = (fn, time) => {
// #1
let bBar = true
return function (e) {
// #2
if (bBar) {
// #3
bBar = false
setTimeout(() => {
fn.call(this, e)
// #4
bBar = true
}, time)
}
}
} */
/* const throttle = (fn, time) => {
// #1
let bBar = true
return function (e) {
// #2
if (!bBar) return
// #3
bBar = false
setTimeout(() => {
fn.call(this, e)
// #4
bBar = true
}, time)
}
} */
// 需求:封装一个 throttle 函数来实现节流的效果
oDiv.onmousemove = _.throttle(function (e) {
let left = e.pageX - this.offsetLeft
let top = e.pageY - this.offsetTop
this.innerHTML = `x: ${left},y: ${top}`
}, 1000);
</script>
</body>
</html>
补充: