Debounce

Debounce - Explanation

어려움 함수 O(1) O(1)

Problem Summary

Write a debounce function that delays invoking a function until after a wait period.

Go to Problem →

Detailed Explanation

이 문제는 **디바운스(debounce)** 패턴을 구현하여 연속된 호출 중 마지막 호출만 실행하는 방법을 학습합니다. ## 핵심 개념: 디바운스 디바운스는 연속된 이벤트 중 마지막 이벤트만 처리하는 기법입니다. ### 접근 방법 ```javascript function debounce(fn, wait) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => fn.apply(this, args), wait); }; } ``` ### 동작 원리 1. 함수 호출 시 타이머 설정 2. 대기 시간 내에 다시 호출되면 타이머 초기화 3. 대기 시간이 지나면 함수 실행 ### 시각화 ``` 호출: --X--X--X--X----------> 실행: ----------------X-----> ^wait 시간 후 마지막 호출 실행 ``` ### 실무 활용 - 검색 입력창 자동완성 (타이핑 완료 후 검색) - 윈도우 리사이즈 이벤트 - 버튼 중복 클릭 방지 - 폼 자동 저장 디바운스는 과도한 API 호출을 방지하고 성능을 최적화합니다.

Solution Code

solution.js
function debounce(fn, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), wait);
  };
}

Key Concepts from This Problem

1. 디바운스
2. setTimeout
3. clearTimeout
4. 이벤트 최적화

Common Mistakes

clearTimeout 없이는 모든 호출이 실행됩니다
this 바인딩을 위해 일반 함수를 사용해야 합니다
즉시 실행이 필요하면 leading 옵션을 구현해야 합니다

Hints

Hint 1: setTimeout과 clearTimeout을 사용하세요.

Complexity Analysis

Time Complexity

O(1)

Constant time regardless of input size

Space Complexity

O(1)

Uses almost no additional memory

Related Tags

#함수 #디바운스 #비동기