1.什么是节流?
答:节流是针对响应跟不上触发频率这类问题的一种解决方案(另一种是防抖)。
节流就是指连续触发事件但是在 n 秒中只执行一次函数。它会稀释函数的执行频率。
2.为什么需要节流?
答:答:一些高频的函数操作比如resize,input,scroll, mousemove可能产生不好的影响,例如事件执行一次就要调用一次ajax。
<!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>debounce</title>
</head>
<style>
#box {
width: 100%;
height: 300px;
background-color: #eee;
color: red;
font-size: 30px;
text-align: center;
font-weight: 700;
line-height: 300px;
}
</style>
<body>
<div id="box"></div>
<script>
var count = 1;
var oBody = document.getElementById('box');
function getUserAction() {
oBody.innerHTML = count++;
}
oBody.addEventListener('mousemove', getUserAction, false)
</script>
</body>
</html>
3.节流怎么实现?
oBody.addEventListener('mousemove', throttle(getUserAction, 1000), false)
function throttle(func, delay) {
let startTime = Date.now()
return function () {
let contxt = this
let args = arguments
let curTime = Date.now()
if (curTime - startTime >= delay) {
func.apply(contxt, args)
startTime = curTime
}
}
}
function throttle(func, delay) {
let timer = null
return function () {
let contxt = this
let args = arguments
if (!timer) {
timer = setTimeout(() => {
func.apply(contxt, args)
clearTimeout(timer)
timer = null
}, delay)
}
}
}
4.平常开发的应用场景
监听页面的滚动事件
鼠标移动事件
游戏中的一些设计
用户缩放浏览器的resize事件