防抖:将多次触发变成只执行最后一次
<input type="text">
<input type="submit" id="input">
<script>
let btn = document.getElementById('input')
btn.addEventListener('click', debounce(submit), false)
function submit(e) {
console.log(1);
}
function debounce(fn) {
let t = null;
return function () {
let f = !t
if(t){
clearTimeout(t)
}
if (f) {
fn.apply(this, arguments)
}
t = setTimeout(() => {
t = null
}, 1000)
}
}
</script>
节流:没隔一段时间执行一次
<input type="text">
<input type="submit" id="input">
<script>
let btn = document.getElementById('input')
btn.addEventListener('click', debounce(submit), false)
function submit(e) {
console.log(1);
}
function debounce(fn){
let begin = 0;
return function(){
let cur = new Date().getTime()
if(cur - begin > 1000){
fn.apply(this, arguments)
begin = cur
}
}
}
</script>