Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Last active November 5, 2022 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoarLin/b1184d6130120532a2e70e948569e05a to your computer and use it in GitHub Desktop.
Save SoarLin/b1184d6130120532a2e70e948569e05a to your computer and use it in GitHub Desktop.
throttle and debounce sample and test code
// 適用場景:偵測 input 做搜尋或自動完成
// inputEl.addEventListener('keyup', debounce(func, 500));
function debounce(func, delay = 200) {
let timer = null;
return (...args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
}
}
let a = function(name) {
console.log('hello ' + name);
}
let b = debounce(a.bind(this, 'debounce'), 2000);
let c = throttle(a.bind(this, 'throttle'), 2000);
b();
c();
b(); // do not execute
c(); // do not execute
setTimeout(()=>{
b(); c();
},2100)
// 適用場景:畫面resize or scroll偵測
// window.addEventListener('resize', throttle(func, 500));
function throttle(func, delay = 200) {
let timer = null, inTrottle = false;
return (...args) => {
if (inTrottle) return;
inTrottle = true;
clearTimeout(timer);
// if func need execute early, remember to remove func.apply in the setTimeout
// let args = arguments;
// func.apply(this, args);
timer = setTimeout(() => {
func.apply(this, args); // if func need execute early, remote this line
inTrottle = false;
}, delay)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment