js代码-防抖函数(立即执行和非立即执行)
作者:互联网
防抖
即执行
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));
标签:function,delay,防抖,debounce,flag,js,立即,timeid,fn 来源: https://blog.csdn.net/Webqianduan_hjq/article/details/120183972