节流与防抖
<!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,
.argbox {
width: 200px;
height: 200px;
background: #168fe6;
margin-top: 20px;
}
</style>
</head>
<body>
<h2>防抖函数封装</h2>
<input type="text" class="input1" placeholder="请输入电话号码" />
<h2>防抖函数传参数</h2>
<input type="text" class="input2" placeholder="请输入电话号码" />
<h2>节流函数封装</h2>
<div class="box"></div>
<h2>节流函数传参数</h2>
<div class="argbox"></div>
<script>
let telInput = document.querySelector('.input1');
telInput.addEventListener('input', antiShake(demo, 2000));
function antiShake(fn, wait) {
let timeOut = null;
return function () {
if (timeOut) clearTimeout(timeOut);
timeOut = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
}
function demo() {
console.log('请求数据');
}
function antiShakearg(e) {
console.log('请求数据', e.target.value);
}
let telInputarg = document.querySelector('.input2');
let antiShakeFunc = antiShake(antiShakearg, 2000);
telInputarg.addEventListener('input', function (e) {
antiShakeFunc(e);
});
let box = document.querySelector('.box');
box.addEventListener('mousemove', throttle(demo, 2000));
function throttle(event, time) {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(() => {
event.apply(this, arguments);
timer = null;
}, time);
}
};
}
function demoarg(e) {
console.log('请求数据', e.clientX, e.clientY);
}
let argbox = document.querySelector('.argbox');
let throttleargFunc = throttle(demoarg, 2000);
argbox.addEventListener('mousemove', function (e) {
throttleargFunc(e);
});
</script>
</body>
</html>