1. 防抖
触发多次只要最后一次
<script>
document.getElementById("input").oninput = debounce(function (args) {
console.log(this);
console.log(args);
}, 500)
// 触发多次只要最后一次
function debounce(cb, delay) {
let t = null;
return function (args) {
if (t != null) {
clearTimeout(t);
}
t = setTimeout(() => {
cb.call(this, args)
}, delay)
}
}
</script>
2. 节流
高频次数限制频率
window.onscroll = throttle(function (args) {
console.log("thisthisthisthis");
console.log(args);
}, 500)
// 高频次数限制频率
function throttle(cb, delay) {
let timer = null;
return function (args) {
if (!timer) {
timer = setTimeout(() => {
cb.call(this, args)
timer = null
}, delay)
}
}
}