Study Note #1: Debounce and Throttle

FeJW
Nov 13, 2020

Introduction

Debounce and Throttle function is used to reduce the number of execution to the event handler function of DOM events that happens frequently. In some frequent happening DOM events, for example: resize, scroll, mouse events, keyboard events, if every event trigger executes the handler function once, it will definitely cause bad performance in browser, as well as laggy user experience.

Debounce

Definition: Given a wait period, the time difference between event handler execution now and the next execution must be bigger than the wait period. If the event is triggered within the waiting period, then the start point of waiting period should be reset to event trigger timestamp.

Debounce Example

Debounce Timeline

From the above timeline, every event trigger resets the starting point of wait period, and handler function is executed only after the wait period ends.

Code Example

Throttle

Definition: In a given time period, no matter how many times the event has been triggered, handler function shall execute only the first time when event happens.

Throttle timeline

From the above timeline, we can see

  • In the first case, red block shows handler function executes when the first time event is detected. Then, wait time starts. During 1000 ms wait time, the second event trigger does not execute handler function.
  • Second case shows the same thing, and the next handler function execution should happen when an event is detected after the given wait time.

Code Example

--

--