节流案例
<!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>
.box {
width: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
const box = document.querySelector('.box')
let i = 1
// 鼠标移动函数
function mouseMove() {
box.innerHTML = ++i
}
// 节流函数
function thottle(fn, t) {
// 起始时间
let startTime = 0
return function () {
// 得到现在的时间
let now = Date.now()
// 判断大于等于500 调用函数
if (now - startTime >= t) {
fn()
// 执行完成后将现在的时间赋值给起始时间
startTime = now
}
}
}
box.addEventListener('mousemove', thottle(mouseMove, 500))
</script>
</body>
</html>