Skip to content

Commit 19cdf5e

Browse files
committed
Provide accurate examples of debounce and throttling
1 parent 6a5e81c commit 19cdf5e

File tree

1 file changed

+78
-48
lines changed

1 file changed

+78
-48
lines changed

README.md

Lines changed: 78 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -8449,70 +8449,100 @@
84498449
84508450
437. ### What is debouncing?
84518451
8452-
Debouncing is a programming pattern that allows delaying execution of some piece of code until a specified time to avoid unnecessary _CPU cycles and API calls_. This in turn enhance the web page performance. The debounce function make sure that your code is only triggered once per user input. The common usecases are Search box suggestions, text-field auto-saves, and eliminating double-button clicks.
8452+
Debouncing is a programming technique used to limit how often a function is executed. Specifically, it ensures that a function is only triggered after a certain amount of time has passed since it was last invoked. This prevents unnecessary or excessive function calls, which can help optimize performance and reduce unnecessary CPU usage or API requests.
84538453
8454-
Let's say you want to show suggestions for a search query, but only after a visitor has finished typing it. So here you write a debounce function where the user keeps writing the characters with in 500ms then previous timer cleared out using `clearTimeout` and reschedule API call/DB query for a new time—300 ms in the future.
8454+
For example, when a user types in a search box, you typically want to wait until they’ve finished typing before fetching suggestions. Without debouncing, an API call would be triggered on every keystroke, potentially causing performance issues. With debouncing, the function call is postponed until the user stops typing for a specified period (e.g., 300ms). If the user types again before this time elapses, the timer resets.
84558455
8456-
```js
8457-
function debounce(func, timeout = 500) {
8458-
let timer;
8459-
return function (...args) {
8460-
clearTimeout(timer);
8461-
timer = setTimeout(() => {
8462-
func.apply(this, args);
8463-
}, timeout);
8464-
};
8465-
}
8466-
function fetchResults() {
8467-
console.log("Fetching input suggestions");
8468-
}
8469-
const processChange = debounce(() => fetchResults());
8470-
```
8456+
**Typical use cases for debouncing include:**
84718457
8472-
The _debounce()_ function can be used on input, button and window events.
8458+
* Search box suggestions (wait until typing pauses before fetching results)
8459+
* Auto-saving text fields (save only after the user stops typing)
8460+
* Preventing double-clicks on buttons
8461+
* Handling window resize or scroll events efficiently
84738462
8474-
**Input:**
8463+
**Example Debounce Function:**
84758464
8476-
```html
8477-
<input type="text" onkeyup="processChange()" />
8478-
```
8465+
JavaScript
8466+
8467+
```css
8468+
function debounce(func, timeout = 500) {
8469+
let timer;
8470+
return function (...args) {
8471+
clearTimeout(timer);
8472+
timer = setTimeout(() => {
8473+
func.apply(this, args);
8474+
}, timeout);
8475+
};
8476+
}
8477+
```
84798478
8480-
**Button:**
8479+
**Usage Example:**
84818480
8482-
```html
8483-
<button onclick="processChange()">Click me</button>
8484-
```
8481+
JavaScript
84858482
8486-
**Windows event:**
8483+
```css
8484+
function fetchResults() {
8485+
console.log("Fetching input suggestions");
8486+
}
8487+
const processChange = debounce(fetchResults, 300);
84878488

8488-
```html
8489-
window.addEventListener("scroll", processChange);
8490-
```
8489+
// Attach to input element
8490+
<input type="text" onkeyup="processChange()" />
84918491

8492-
**[⬆ Back to Top](#table-of-contents)**
8492+
// Attach to button
8493+
<button onclick="processChange()">Click me</button>
8494+
8495+
// Attach to window event
8496+
window.addEventListener("scroll", processChange);
8497+
```
8498+
8499+
**How it works:**
8500+
When `processChange` is invoked (e.g., by typing or clicking), any pending execution is canceled, and the function is scheduled to run after the specified delay. If another event occurs before the delay is up, the timer resets, and the function will only run after events have stopped for the delay duration.
8501+
8502+
Debouncing is an essential tool for improving user experience and application performance, especially when dealing with events that can fire rapidly and repeatedly.
8503+
8504+
**[⬆ Back to Top](#table-of-contents)**
84938505
84948506
438. ### What is throttling?
8507+
Throttling is a programming technique used to control the rate at which a function is executed. When an event is triggered continuously—such as during window resizing, scrolling, or mouse movement—throttling ensures that the associated event handler is not called more often than a specified interval. This helps improve performance by reducing the number of expensive function calls and preventing performance bottlenecks.
84958508
8496-
Throttling is a technique used to limit the execution of an event handler function in a given period of time, even when this event triggers continuously due to user actions. The common use cases are browser resizing, window scrolling, mouse movements etc.
8509+
**Common use cases:**
84978510
8498-
The below example creates a throttle function to reduce the number of events for each pixel change and trigger scroll event for each 100ms except for the first event.
8511+
* Window resize events
8512+
* Scroll events
8513+
* Mouse movement or drag events
8514+
* API rate limiting
84998515
8500-
```js
8501-
const throttle = (func, limit) => {
8502-
let inThrottle;
8503-
return (...args) => {
8504-
if (!inThrottle) {
8505-
func.apply(this, args);
8506-
inThrottle = true;
8507-
setTimeout(() => (inThrottle = false), limit);
8508-
}
8509-
};
8510-
};
8511-
window.addEventListener("scroll", () => {
8512-
throttle(handleScrollAnimation, 100);
8513-
});
8514-
```
8516+
**How does throttling work?**
8517+
Throttling will execute the function at most once every specified time interval, ignoring additional calls until the interval has passed.
8518+
8519+
**Example: Throttle Implementation and Usage**
8520+
8521+
JavaScript
85158522
8523+
```css
8524+
// Simple throttle function: allows 'func' to run at most once every 'limit' ms
8525+
function throttle(func, limit) {
8526+
let inThrottle = false;
8527+
return function(...args) {
8528+
if (!inThrottle) {
8529+
func.apply(this, args);
8530+
inThrottle = true;
8531+
setTimeout(() => (inThrottle = false), limit);
8532+
}
8533+
};
8534+
}
8535+
8536+
// Usage: throttling a scroll event handler
8537+
function handleScrollAnimation() {
8538+
console.log('Scroll event triggered');
8539+
}
8540+
8541+
window.addEventListener(
8542+
"scroll",
8543+
throttle(handleScrollAnimation, 100) // Will run at most once every 100ms
8544+
);
8545+
```
85168546
**[⬆ Back to Top](#table-of-contents)**
85178547
85188548
439. ### What is optional chaining?

0 commit comments

Comments
 (0)