-
[JavaScript] Throttle 와 DebounceJavaScript 2022. 6. 23. 23:19
Throttle 와 Debounce
- 성능 최적화를 위해 이벤트의 횟수를 제어하는 기법
- 스크롤 이벤트 리스너를 등록하면 스크롤 할 때마다 수 많은 스크롤 이벤트가 발생한다.
window.addEventListener("scroll", () => console.log("scroll!"));
Throttle
이벤트를 일정한 주기마다 한 번만 발생하도록 한다.
일정 주기를 1초로 설정한다면, 10초 동안 계속 이벤트를 발생시켜도 10번만 호출이 된다.
Debounce
특정 시간이 지나야 이벤트가 한 번 발생한다. 연속되는 이벤트 호출이 그룹으로 묶이게 된다.
ex)
- 검색 API 호출 (자동완성) : "안녕"을 검색하면 'ㅇ', '아', '안' '안ㄴ', '안녀' 과 같이 불필요한 요청들을 막아준다.
- 브라우저 리사이즈 이벤트 : 사용자가 브라우저 창 크기 조절이 끝날 때 이벤트가 한 번만 실행할 수 있게 할 수 있다.
반응형'JavaScript' 카테고리의 다른 글
[JavaScript] FileReader 객체 (0) 2022.09.11 [JavaScript] use strict (0) 2022.08.30 [JavaScript] var let const 차이점 (0) 2022.08.08 [JavaScript] 키보드 이벤트: 특정키 확인 (key, code, keyCode) (0) 2022.07.18 [JavaScript] 브라우저 창 사이즈 (0) 2022.06.16