<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>节流和防抖示例</title>
<style type="text/css">
body {
height: 3000px;
}
.box {
width:100px;
height: 100px;
overflow: scroll;
font-size: 12px;
}
.box div {
height: 3000px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>
</head>
<body>
<!-- <div class="box" id="box1" style="background: yellow;">
<div>测试<span style="font-size:30px">节流</span>(首次不执行)</div>
</div>
<div class="box" id="box2" style="background: red;">
<div>测试<span style="font-size:30px">节流</span>(首次执行)</div>
</div> -->
<input id="ipt" placeholder="测试防抖(首次不执行)">
<button id="btn">111测试防抖首次执行(自己写的简化版)</button>
<button id="btn2">2222测试防抖首次执行,到了一定的秒数继续执行(用lodash库)</button>
<button id="btn3">333测试防抖首次执行,到了一定的秒数继续执行(用lodash库)</button>
<script type="text/javascript">
function throttle(fn, delay = 100) {
let timer = null;
return function () {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}
function throttle2(fn, delay = 100) {
let last = 0;
return function () {
let curr = +new Date();
if (curr - last > delay) {
fn.apply(this, arguments);
last = curr;
}
}
}
</script>
<script type="text/javascript">
function debounce(fn, delay = 200) {
let timer = null;
return function () {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}
function debounce2(fn, delay = 200, firstExecutionFlag = true) {
let timer = null, last = 0, during;
return function () {
let self = this, args = arguments;
var exec = function () {
fn.apply(self, args);
}
console.log(firstExecutionFlag, !timer)
if (firstExecutionFlag && !timer) {
console.log(1)
exec();
firstExecutionFlag = false;
} else {
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
exec();
}, delay);
}
}
}
function debounce3(fn, delay = 500, firstExecutionFlag) {
let timer;
return function() {
let that = this,
args = arguments;
if (timer) clearTimeout(timer);
if (firstExecutionFlag) {
let flag = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
if (flag) {
fn.apply(that, args)
}
} else {
timer = setTimeout(() => {
fn.apply(that, args);
}, delay)
}
}
}
document.getElementById('ipt').onkeydown = debounce(function () {
console.log(3);
}, 500);
document.getElementById('btn').onclick = debounce(function () {
console.log(4);
}, 1000, 1);
document.getElementById('btn2').onclick = debounce2(function () {
console.log(4, debounce2(function () {console.log('123')}));
});
document.getElementById('btn3').onclick = debounce3(function () {
console.log(4);
}, 1000, true);
</script>
</body>
</html>