防抖
即执行
function debounce(fn, delay) {
let timeid=null, flag = true;
return function () {
clearTimeout(timeid);
if (flag) {
fn();
flag = false;
} else {
timeid = setTimeout(function () {
flag = true;
}, delay);
}
}
}
document.getElementById("myBtn").addEventListener("click", debounce(() => {
console.log('调用成功');
}, 3000));
//非立即执行
function debounce(fn, delay) {
let timeid = null;
return function () {
if (timeid) {
clearTimeout(timeid);
}
timeid = setTimeout(fn, delay);
}
}
document.getElementById("myBtn").addEventListener("click", debounce(() => {
console.log('调用成功');
}, 2000));