Skip to content

Instantly share code, notes, and snippets.

@xiaoliang2233
Last active July 7, 2021 10:53
Show Gist options
  • Save xiaoliang2233/a498341d5c54083d2f0f6debe235a4e4 to your computer and use it in GitHub Desktop.
Save xiaoliang2233/a498341d5c54083d2f0f6debe235a4e4 to your computer and use it in GitHub Desktop.
debounceTime, auditTime, throttleTime
/**
* auditTime 是每次点击开始计时, 超时的时候再emit最近的一次事件
*
* throttleTime 是每次点击emit事件, 之后的一段时间不会再触发事件
*
* debounceTime 是每次点击重新计时, 超时的时候emit此事件
*/
let print = auditTime(1000, e => {
console.log('😋', e)
});
document.documentElement.addEventListener('click', e => {
print(e);
}, false);
function auditTime(time, callback) {
let timer;
return e => {
if (timer) {
return;
}
callback && callback(e);
timer = setTimeout(_ => {
timer = null;
}, time)
}
}
function debounceTime(time, callback) {
let timer;
return (e) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(_ => {
callback && callback(e);
timer = null;
}, time)
}
}
function throttleTime(time) {
let now, before;
return _ => {
now = (new Date).getTime();
if (!before || now - before > time) {
before = now;
return true;
}
before = now;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment