防抖(先后) immediate为true(先执行) false(后执行)
function debounce(func, wait, immediate) {
let timeout;
return function () {
if (timeout) clearTimeout(timeout);
if (immediate) {
const callNow = !timeout;
timeout = setTimeout(function () {
timeout = null;
}, wait)
if (callNow) func.apply(this, arguments)
} else {
timeout = setTimeout(function () {
func.apply(this, arguments)
}, wait);
}
}
}
节流(先后) immediate为true(先执行) false(后执行)
- 应用场景 resize窗口大小变化事件和滚动条滑动事件做个时间的间隔触发
function throttle(func, wait, immediate) {
let timeout;
debugger
return function () {
debugger
if (!timeout) {
if (immediate) {
func.apply(this, arguments)
timeout = setTimeout(function () {
timeout = null;
}, wait)
} else {
timeout = setTimeout(function () {
timeout = null;
func.apply(this, arguments)
}, wait)
}
}
}
}