JavaScript
Throttle & Debounce
kelly09
2024. 6. 30. 10:33
๐ฐ ๋ ๋ค JavaScript์์ ์ฑ๋ฅ ์ต์ ํ๋ฅผ ์ํด ํน์ ์ด๋ฒคํธ์ ํธ์ถ ๋น๋๋ฅผ ์ ์ดํ๋ ๋ฐ ์ฌ์ฉ๋จ.
๐ด Throttle
: ์ด๋ฒคํธ๊ฐ ์ฐ์ํด์ ๋ฐ์ ์, ์ผ์ ์๊ฐ ๊ฐ๊ฒฉ์ผ๋ก ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํจ.
- ์ด๋ฒคํธ๊ฐ ์์ฃผ ๋ฐ์ํด๋ ์ผ์ ์๊ฐ๋ง๋ค ํ ๋ฒ์ฉ๋ง ์ฒ๋ฆฌ๋จ.
let waiting = false;
function throttle(callback, limit = 200) {
if (!waiting) { // waiting์ด false์ผ ๋๋ง ์คํ
callback();
waiting = true;
setTimeout(() => { // limit์ด ๋ค์ waiting์ false๋ก ๋ณ๊ฒฝํ๋ ํ์ด๋จธ
waiting = false;
}, limit);
}
}
- ํ์ด๋จธ๊ฐ ๋๊ณ ์๋ ์์ค์ throttle ํจ์๋ฅผ ๊ณ์ ํธ์ถํด๋ waiting์ด true๋๊น ๋๋จธ์ง๋ ์คํ๋์ง ์์
- limit์ด๊ฐ ์ง๋ ํ waiting์ด false๊ฐ์ด ๋๋ฉด ๋ค์ if๋ฌธ์ ๋๋ฉด์ callback()์ ๋ค์ ์คํ์ํด
- ๋ค์ ํ์ด๋จธ๊ฐ ๋์๊ฐ๊ณ ๋ฐ๋ณต...
์ ํจ์๋ฅผ closure๋ก ์์ !
const ground = document.querySelector(".ground");
let waiting = false;
function throttle(callback) {
if (!waiting) {
callback();
waiting = true;
setTimeout(() => {
waiting = false;
}, 1000);
}
}
ground.addEventListener("mousemove", (e) => { // event ๊ฐ์ฒด ์ ๋ฌํ๋ฉด throttle()์ ์์ชฝ ํจ์์ ๋งค๊ฐ๋ณ์๋ก ๋ค์ด๊ฐ์
// throttle์์ ๋ฐ์์ ์ธ ์ ์์
console.log(e);
});
- ํจ์๋ฅผ returnํ๋ ํ์
- throttle()์ ์คํ์ํด => ์์ชฝ ํจ์๊ฐ ๋ฐํ๋จ => ์์ชฝ ํจ์๋ฅผ ์คํ์์ผ์ผ ํจ! throttle(()=>{
console.log('์๋ ');})์ด๋ฐ ์์ผ๋ก.
๊ทธ๋ฐ๋ฐ ๋ง์ฝ this๋ฅผ ์ฌ์ฉํด์ผ ํ ๊ฒฝ์ฐ๊ฐ ์๊ธธ ์! this๋ ์ด๋ป๊ฒ ์ฐพ์์ผ ํ๋?
const ground = document.querySelector(".ground");
let waiting = false;
function throttle(callback, limit = 200) {
let waiting = false;
return function (e) { // ์ด ํจ์๊ฐ mousemove์ ์ํด ์คํ๋จ -(2)
// ์ด ํจ์๋ ๋ณธ์ธ์ด ๋๊ตฌ์ ์ํด ์คํ๋๋์ง ์๊ณ ์์ -(3)
console.log(this); // ์ด this๋ ๋๋ฅผ ํธ์ถํ ๋์์ธ ground์ -(4)
if (!waiting) {
callback.call(this, e); // ๊ทธ๋์ call ์ด์ฉ -(6)
waiting = true;
setTimeout(() => {
waiting = false;
}, limit);
}
};
}
ground.addEventListener('mousemove', throttle(function() { // throttle์ด ์คํ๋จ๊ณผ ๋์์ -(1)
// throttle์ ํธ์ถํ ๋์์ ๋ชจ๋ฆ. ๋ณธ์ธ์ด ์์์ ์คํํจ. -(5)
console.log(this);
}));
๐ด Debounce
: ์งง์ ์๊ฐ ๊ฐ๊ฒฉ์ผ๋ก ์ด๋ฒคํธ๊ฐ ์ฐ์ํด์ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ํธ๋ค๋ฌ๋ฅผ ํธ์ถํ์ง ์๋ค๊ฐ ์ผ์ ์๊ฐ ๊ฒฝ๊ณผ ํ ์ด๋ฒคํธ ํธ๋ค๋ฌ๊ฐ ํ ๋ฒ๋ง ํธ์ถ๋๋๋ก ํจ.
const searchInput = document.querySelector('#search-input');
const searchAPI = (query) => {
// ๊ฒ์ API ํธ์ถ ์ฝ๋
console.log(`๊ฒ์์ด: ${query}`);
};
const debouncedSearch = debounce(searchAPI, 300);
// searchAPI ํจ์๋ฅผ 300 ๋ฐ๋ฆฌ์ด ๋์ ์ง์ฐ์ํด
// ์ฌ์ฉ์๊ฐ 300๋ฐ๋ฆฌ์ด ์ด๋ด์ ๋ค๋ฅธ ๋ฌธ์ ์
๋ ฅ -> ์ด์ ๊ฒ์ API ํธ์ถ์ ์ทจ์๋๊ณ
// ๋ง์ง๋ง ์
๋ ฅ ๋ฌธ์๋ก๋ง ๊ฒ์ ์ํ
searchInput.addEventListener('input', (event) => { // ์ฌ์ฉ์๊ฐ ์
๋ ฅํ ๋๋ง๋ค ํด๋น ํจ์ ์คํ
const query = event.target.value;
debouncedSearch(query);
});