<body>
<!-- 输入框 -->
<input type="text" id="my-input">
<!-- JS -->
<script>
// 防抖
function debounce (fn, delay) {
var delay = delay || 200
var timer = null
return function () {
var that = this
var args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function () {
timer = null
fn.apply(that, args)
}, delay)
}
}
// 节流
function throttle (fn, interval) {
var last = null
var timer = null
var interval = interval || 200
return function () {
var that = this
var args = arguments
var now = +new Date()
if (last && now - last < interval) {
clearTimeout(timer)
timer = setTimeout(function () {
last = now
fn.apply(that, args)
}, interval)
} else {
last = now
fn.apply(that, args)
}
}
}
// 输入监听
const input = document.getElementById('my-input')
input.oninput = throttle(function (e) {
console.log(e.target.value)
}, 500)
</script>
</body>