Skip to content

onScroll event에 throttle을 적용하는 방법 #630

Answered by woohm402
HyeongtaekOh asked this question in Q&A
Discussion options

You must be logged in to vote

이래서 타입스크립트를 권장드립니다 ㅎ

lodash 오픈소스 뜯어볼게요 (커밋 7b62f878cc218c8e94e6efafa55cea6796b501f7 기준)

lodashthrottle 함수는 세 가지 인자를 받아서 함수를 리턴합니다. 타입스크립트 식으로 쓰면 다음과 같습니다. (소스)

DebouncedFunc 는 여기 있는데, 실행할 수 있는 함수에 뭐 좀 더해서 돌려줍니다. 또한 ThrottleSettings는 여기 있네요

type lodash = (func: (...args: any) => any, wait?: number, options?: ThrottleSettings) => DebouncedFunc<T>

그래서 이 친구의 사용법이 보통 어떠냐면

const sayHello = () => {
  console.log('Hello World!');
}

const throttledHello = throttle(sayHello, 1000);

return <button onClick={throttledHello}>클릭</button>

위 코드를 보면 버튼을 클릭할 때마다 throttledHello 함수가 실행됩니다. throttledHello는 throttle이 반환한 특이한 함수를 가리키는데, 1000ms 동안은 콜백으로 받은 첫 번째 함수 (이 경우 sayHello) 를 한 번씩만 실행하는 함수입니다.

따라서 실행 결과…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@HyeongtaekOh
Comment options

HyeongtaekOh Nov 5, 2021
Collaborator Author

Answer selected by HyeongtaekOh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
React React 관련 내용
2 participants