Skip to content

Instantly share code, notes, and snippets.

@Debbl
Last active March 18, 2022 07:50
Show Gist options
  • Save Debbl/efe05c4435297693d497f875e7f3251b to your computer and use it in GitHub Desktop.
Save Debbl/efe05c4435297693d497f875e7f3251b to your computer and use it in GitHub Desktop.
手写防抖函数
function debounce(fn, delay) {
// 定时器,保留上一个触发的定时器
let timer = null;
const _debounce = function () {
// 没有达到延时,在次触发,清空上一次的定时器,不执行 fn
if (timer) clearTimeout(timer);
// 定时器
timer = setTimeout(() => {
fn();
}, delay);
};
return _debounce;
}
function debounce(fn, delay) {
// 定时器,保留上一个触发的定时器
let timer = null;
const _debounce = function (...args) {
// 没有达到延时,在次触发,清空上一次的定时器,不执行 fn
if (timer) clearTimeout(timer);
// 定时器
timer = setTimeout(() => {
// this args
fn.apply(this, args);
}, delay);
};
return _debounce;
}
function debounce(fn, delay, immediate = false) {
// 定时器,保留上一个触发的定时器
let timer = null;
let isInvoke = false; // 是否立即执行
const _debounce = function (...args) {
// 没有达到延时,在次触发,清空上一次的定时器,不执行 fn
if (timer) clearTimeout(timer);
// 立即执行
if (immediate && !isInvoke) {
fn.apply(this, args);
isInvoke = true;
} else {
// 定时器
timer = setTimeout(() => {
// this args
fn.apply(this, args);
isInvoke = false;
}, delay);
}
};
return _debounce;
}
function debounce(fn, delay, immediate = false, resultCallback) {
// 定时器,保留上一个触发的定时器
let timer = null;
let isInvoke = false; // 是否立即执行
const _debounce = function (...args) {
return new Promise((resolve) => {
// 没有达到延时,在次触发,清空上一次的定时器,不执行 fn
if (timer) clearTimeout(timer);
// 立即执行
if (immediate && !isInvoke) {
const result = fn.apply(this, args);
if (resultCallback && typeof resultCallback === 'function')
resultCallback(result);
resolve(result);
isInvoke = true;
} else {
// 定时器
timer = setTimeout(() => {
// this args
const result = fn.apply(this, args);
if (resultCallback && typeof resultCallback === 'function')
resultCallback(result);
resolve(result);
isInvoke = false;
timer = null;
}, delay);
}
});
};
return _debounce;
}
function debounce(fn, delay, immediate = false, resultCallback) {
// 定时器,保留上一个触发的定时器
let timer = null;
let isInvoke = false; // 是否立即执行
const _debounce = function (...args) {
return new Promise((resolve) => {
// 没有达到延时,在次触发,清空上一次的定时器,不执行 fn
if (timer) clearTimeout(timer);
// 立即执行
if (immediate && !isInvoke) {
const result = fn.apply(this, args);
if (resultCallback && typeof resultCallback === 'function')
resultCallback(result);
resolve(result);
isInvoke = true;
} else {
// 定时器
timer = setTimeout(() => {
// this args
const result = fn.apply(this, args);
if (resultCallback && typeof resultCallback === 'function')
resultCallback(result);
resolve(result);
isInvoke = false;
timer = null;
}, delay);
}
});
};
// 取消功能
_debounce.cancel = function () {
if (timer) clearTimeout(timer);
timer = null;
isInvoke = false;
};
return _debounce;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment