防抖节流
多说无益,代码示意
<!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: 600px;
height: 300px;
background-color: grey;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
const box = document.getElementById('box')
// box.addEventListener('mousemove', debounce(handle, 1000)) // 鼠标一直移动,直到不移动的时候执行
// box.addEventListener('mousemove', throttle(handle, 1000)) // 鼠标一直移动,每隔几秒执行一次
function handle(e) {
console.log(e);
}
function debounce(fn, delay) {
let timer = 0;
return function (...args) {
let that = this;
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(that, args)
}, delay)
}
}
function throttle(fn, delay) {
let timer = 0;
return function (...args) {
let that = this;
if (timer) return;
fn.apply(that, args)
timer = setTimeout(() => {
clearTimeout(timer)
timer = 0;
}, delay)
}
}
</script>
</body>
</html>

浙公网安备 33010602011771号