Last active
November 5, 2022 07:00
-
-
Save SoarLin/b1184d6130120532a2e70e948569e05a to your computer and use it in GitHub Desktop.
throttle and debounce sample and test code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 適用場景:偵測 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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 適用場景:畫面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