<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> 防抖和节流 </title>
</head>
<body>
<input type=""name="" id="input" value="" />
<script>
const debounce = function(fn, delay = 300) {
let timer = null
return function() {if (timer) clearTimeout(timer)
timer = setTimeout(() => {fn.apply(null, arguments)
timer = null
}, delay)
}
}
const throttle = function(fn, delay = 300) {
let timer = null
return function() {if (timer) return
timer = setTimeout(() => {fn.apply(null, arguments)
timer = null
}, delay)
}
}
// 防抖测试
const input = document.getElementById('input')
input.addEventListener('input', debounce((ev) => {console.log(ev.target.value)
}, 500))
// 节流测试
window.addEventListener('resize', throttle((ev) => {console.log('resize', ev)
}, 500))
</script>
</body>
</html>