/**
* @desc 函数防抖---“立即执行版本” 和 “非立即执行版本” 的组合版本
* @param func 需要执行的函数
* @param wait 延迟执行时间(毫秒)
* @param immediate---true 表立即执行,false 表非立即执行
**/
// "use strict";
function debounce(func, wait, immediate) {
let timer;
return () => {
// let context = this;
const args = arguments;
if (timer) clearTimeout(timer);
if (immediate) {
const callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait)
if (callNow) func.apply(this, args)
} else {
timer = setTimeout(() => {
func.apply(this, args)
}, wait);
}
}
}
// function handle() {
// const _this = this
// console.log(Math.random(), _this === window);
// }
// // window.addEventListener("mousemove", debounce(handle, 1000, true)); // 调用立即执行版本
// window.addEventListener("mousemove", debounce(handle, 1000, false)); // 调用非立即执行版本
window.addEventListener("mousemove", debounce(() => {
const _this = this
console.log(Math.random(), _this === window);
}, 1000, true));