防抖&节流 手写实现
javascript 性能优化 防抖 节流
防抖
<!DOCTYPE html>
<html>
<head>
<title>TestDebounce</title>
<script type="text/javascript">
function debounce(fn, time = 300) {
let timer;
return function (...args) {
timer && clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
timer = null;
}, time);
};
}
function show(a, b, c) {
console.log(a + b + c);
}
window.onload = function () {
let input = document.getElementById("input");
input.addEventListener(
"input",
debounce(show).bind(this, 123, 123, 123)
);
};
</script>
</head>
<body>
<!-- 假设使用下面这种oninput,debounce会执行多次,timer就需要设置成全局变量 -->
<!-- <input id="input" type="" name="" oninput="debounce(show)(123,123,123)"> -->
<!-- 所以使用addEventListener方式会比较好 -->
<input id="input" type="" name="" />
</body>
</html>
节流
<!DOCTYPE html>
<html>
<head>
<title>TestThrottle</title>
<script type="text/javascript">
//定时器版 不会立即执行
// function throttle(fn,time = 1000){
// let timer;
// return function(...args){
// !timer && (timer = setTimeout(() =>{
// fn(...args)
// timer = null;
// },time))
// }
// }
//时间戳版 会立即执行
function throttle(fn, time = 1000) {
let start = 0;
return function (...args) {
let now = Date.now();
if (now - start > time) {
fn(...args);
start = now;
}
};
}
function show(a, b, c) {
console.log(a + b + c);
}
window.onload = function () {
let input = document.getElementById("input");
input.addEventListener("input", throttle(show).bind(this, 1, 2, 3));
};
</script>
</head>
<body>
<input id="input" type="" name="" />
</body>
</html>