防抖
输入结束后n秒才进行搜索, n秒内又输入内容就重新计时(解决搜索bug)
function debounce(fun, delay) {
var timer
return function (args) {
clearInterval(timer)
timer = setTimeout(() => {
fun(args)
}, delay);
}
}
function inputFun(value) {
console.log('您输入的结果是' + value)
}
const input = document.getElementById('input')
debounceInput = debounce(inputFun, 1000)
document.addEventListener('keyup', function (e) {
debounceInput(e.target.value)
})
节流
一段时间内只做一件事情如:表单提交
function throttle(fun, wait) {
let timerOut
return function () {
if (!timerOut) {
timerOut = setTimeout(() => {
timerOut = null
fun()
}, wait);
}
}
}
function handdle() {
console.log(Math.random())
}
document.getElementById('button').onclick = throttle(handdle, 1000)