맨 땅에 프론트엔드 개발자 되기

lodash throttle과 debounce를 이용해서 함수의 반복 실행 막기 본문

코딩 공부 일지/JavaScript

lodash throttle과 debounce를 이용해서 함수의 반복 실행 막기

헬로코딩 2022. 6. 19. 17:02
728x90

Lodash

https://lodash.com/

 

Lodash

_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn

lodash.com

npm i lodash

lodash는 자바스크립트 패키지 중 가장 인기있는 패키지들 중 하나로 정말 많이 사용된다. 주로 array 자료형을 다루기 위해 자바스크립트에서 기본적으로 제공하지 않는 method를 사용하기 위해 쓴다.

 

throttle과 debounce

lodash는 array 자료형 method 뿐 아니라 throttle과 debounce 라는 기능을 제공한다. 두 기능 모두 이벤트의 반복 실행 시 콜백 함수의 불필요한 실행을 막아주는 역할을 한다. 예를 들어, form 양식의 submit 액션을 일으키는 버튼 클릭을 사용자가 여러 번 할 경우, 여러 번 submit 액션이 일어나는 것을 한 번만 액션이 일어나도록 방지할 수 있다.

throttle과 debounce의 차이점은 아래와 같다.

  • throttle: throttle은 '목을 조르다'라는 뜻으로, 버튼 클릭이 콜백 함수를 실행하도록 요청하는 길목을 졸라서 액션이 일어나는 횟수를 줄이는 것이라고 보면 된다. 스크롤 이벤트나 마우스 움직임 감지 이벤트와 같이 동작 감지가 여러번 일어나는 경우에 코드에 지정한 시간마다 한 번 이벤트를 감지하도록 만들 수 있다.
  • debounce: throttle이 맨 처음 이벤트가 발생했을 때 일정 시간 동안의 이벤트를 막고 그 일정 시간 이후에 발생한 이벤트를 다시 실행시킨다면, debounce는 여러 번 이벤트가 발생했을 때 앞에 일어난 이벤트를 취소하고 제일 마지막에 일어난 이벤트를 정해둔 시간동안 기다렸다가 실행한다. 직접 사용해보면 debounce가 throttle보다 더 이벤트 실행을 많이 막는 느낌이다.

throttle 의 실행 예시

import styles from 'pages/sample.module.scss';
import { throttle } from "lodash";

export default function Sample() {
  const onMouseMove = () => {
    console.log('no throttle');
  }
  const onMouseMoveThrottle = throttle(() => {
    console.log('throttle');
  }, 1000); // 1000ms 1초에 한번씩 실행

  return (
    <section 
      className={styles.sample}
      onMouseMove={() => {
        onMouseMove();
        onMouseMoveThrottle();
      }}>
    </section>
  )
}

debounce 의 실행 예시

import styles from 'pages/sample.module.scss';
import { debounce } from "lodash";

export default function Sample() {
  const onMouseMove = e => {
    console.log('no debounce');
  }
  const onMouseMoveDebounce = debounce(e => {
    console.log('debounce');
  }, 1000); // 1000ms 맨 마지막 동작 요청 이후 1초 뒤 동작

  return (
    <section 
      className={styles.sample}
      onMouseMove={() => {
        onMouseMove();
        onMouseMoveDebounce();
      }}>
    </section>
  )
}

throttle과 debounce 를 적절하게 사용하면 성능 향상에 큰 도움이 될 수 있다.

728x90