<!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>
</head>
<body>
<input id="input" type="text">
<button id="button">click</button>
<script>
function debounce(fun, delay) {
let timer;
return function (args) {
clearInterval(timer)
timer = setTimeout(() => {
fun(args)
}, delay);
}
}
function inputFun(value) {
console.log(`你的输出结果是${value}`)
}
const input = document.getElementById("input")
const deboundInput = debounce(inputFun, 500)
input.addEventListener(‘keyup‘, function (e) {
deboundInput(e.target.value)
})
function throttle(func, wait) {
let timerOut;
return function () {
if (!timerOut) {
timerOut = setTimeout(function () {
timerOut = null;
func()
}, wait)
}
}
}
function handle() {
console.log(Math.random())
}
document.getElementById("button").onclick = throttle(handle, 2000)
</script>
</body>
</html>
JS 防抖节流简单应用