1. 防抖
- 防抖,解决触发过于频繁的问题,只需要最后一次触发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>节流和防抖</title>
<link rel="text/css" href="../source/bootstrap.min.css">
</head>
<body>
<!-- 防抖 -->
<script>
function debounce(fn, time) {
let t = null;
return function(...args){
clearTimeout(t);
t = setTimeout(function() {
fn(...args);
}, time);
}
};
const test = debounce((event) => {
console.log('input', event.target.value);
}, 2000);
</script>
<input oninput="test(event)" type="text">
</body>
</html>
按钮防抖,防止重复点击
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>节流和防抖</title>
</head>
<body>
<button id="test">点击-防抖</button>
<button id="test2">点击-不防抖</button>
<!-- 防抖 -->
<script>
function debounce(fn, time) {
let t = null;
return function(...args){
clearTimeout(t);
t = setTimeout(function() {
fn(...args);
}, time);
}
};
window.onload = function () {
let test = document.getElementById('test');
test.onclick = debounce(function() {
console.log('click')
}, 500);
let test2 = document.getElementById('test2');
test2.onclick = function() {
console.log('click-不防抖')
};
}
</script>
</body>
</html>
2. 节流
- 节流,控制执行次数,例如
0.5s
至多执行一次<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>节流和防抖</title>
<link rel="text/css" href="../source/bootstrap.min.css">
</head>
<body style="height: 1000px">
<script>
function throttle(fn, time) {
let flag = true;
return function(...args){
if (flag) {
setTimeout(function() {
fn(...args);
flag = true;
}, time);
}
flag = false;
}
};
</script>
<script>
window.onscroll = throttle(function(event) {
console.log('scroll')
}, 500);
</script>
</body>
</html>