初级版
<!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">
<script src="../js/jquery-3.6.0.min.js"></script>
<title>Document</title>
<script>
$(() => {
let t;
$('input').on('input', (event) => {
if (t != null) {
clearTimeout
}
t = setTimeout(() => {
console.log(event.currentTarget.value);
}, 500);
})
});
//或者
window.onload = function() {
let inp = document.querySelector("input")
let t = null;
inp.oninput = function() {
if (t !== null) {
clearTimeout(t)
}
t = setTimeout(() => {
console.log(this.value);
}, 500);
}
}
</script>
</head>
<body>
<input type="text">
</body>
</html>
晋级版
window.onload = function() {
let inp = document.querySelector("input")
let t = null;
inp.oninput = debounce(function() {
console.log(this.value)
}, 500)
function debounce(fn, delay) {
let t;
return function() {
if (t != null) {
clearTimeout(t)
}
t = setTimeout(() => {
fn.call(this);
}, delay);
}
}
}
节流
<!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">
<script src="../js/jquery-3.6.0.min.js"></script>
<title>Document</title>
<script>
window.onload = function() {
let flag = true
window.onscroll = function() {
if (flag) {
setTimeout(() => {
console.log('123');
flag = true
}, 500);
}
flag = false;
}
}
</script>
</head>
<body style="height: 2000px;">
<input type="text">
</body>
</html>
进阶
<script>
window.onload = function() {
window.onscroll = throttle(() => {
console.log('qweqwe');
}, 500)
function throttle(fn, delay) {
let flag = true
return function() {
if (flag) {
setTimeout(() => {
fn.call(this)
flag = true
}, 500);
flag = false;
}
}
}
}
</script>