0
# Lodash Throttle
1
2
Lodash Throttle provides the `_.throttle` method as a standalone npm module for rate-limiting function calls. It creates throttled functions that only invoke the original function at most once per specified wait period, with configurable leading and trailing edge execution control.
3
4
## Package Information
5
6
- **Package Name**: lodash.throttle
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.throttle`
10
11
## Core Imports
12
13
```javascript
14
var throttle = require('lodash.throttle');
15
```
16
17
For ES modules environments:
18
19
```javascript
20
import throttle from 'lodash.throttle';
21
```
22
23
## Basic Usage
24
25
```javascript
26
var throttle = require('lodash.throttle');
27
28
// Basic throttling - limits function calls to once per 100ms
29
var throttledUpdate = throttle(function(value) {
30
console.log('Update called with:', value);
31
}, 100);
32
33
// Call multiple times quickly - only executes once per 100ms
34
throttledUpdate('a');
35
throttledUpdate('b');
36
throttledUpdate('c');
37
38
// With options for leading/trailing edge control
39
var scrollHandler = throttle(updatePosition, 100, {
40
leading: true,
41
trailing: false
42
});
43
44
window.addEventListener('scroll', scrollHandler);
45
46
// Cancel pending invocations
47
scrollHandler.cancel();
48
49
// Immediately execute pending invocation
50
scrollHandler.flush();
51
```
52
53
## Architecture
54
55
Lodash Throttle is built on top of the debounce implementation with specific configuration to create true throttling behavior:
56
57
- **Internal Implementation**: Uses `debounce` with `maxWait` set equal to the `wait` parameter, ensuring function execution at least once per wait period
58
- **Edge Control**: Configurable leading and trailing edge execution through options
59
- **Timer Management**: Maintains internal timer state with automatic cleanup and reset mechanisms
60
- **Method Attachment**: Dynamically attaches `cancel` and `flush` control methods to the returned throttled function
61
- **Argument Preservation**: Preserves the most recent arguments and `this` context for delayed invocations
62
63
## Capabilities
64
65
### Throttle Function
66
67
Creates a throttled function that only invokes the provided function at most once per every wait milliseconds.
68
69
```javascript { .api }
70
/**
71
* Creates a throttled function that only invokes `func` at most once per
72
* every `wait` milliseconds.
73
* @param {Function} func The function to throttle.
74
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
75
* @param {Object} [options={}] The options object.
76
* @param {boolean} [options.leading=true] Specify invoking on the leading edge of the timeout.
77
* @param {boolean} [options.trailing=true] Specify invoking on the trailing edge of the timeout.
78
* @returns {Function} Returns the new throttled function.
79
*/
80
function throttle(func, wait, options);
81
```
82
83
**Parameters:**
84
- `func` (Function): The function to throttle
85
- `wait` (number, optional): The number of milliseconds to throttle invocations to. Defaults to 0
86
- `options` (Object, optional): The options object with the following properties:
87
- `leading` (boolean, optional): Specify invoking on the leading edge of the timeout. Defaults to true
88
- `trailing` (boolean, optional): Specify invoking on the trailing edge of the timeout. Defaults to true
89
90
**Returns:** Function - The new throttled function with attached `cancel` and `flush` methods
91
92
**Usage Examples:**
93
94
```javascript
95
var throttle = require('lodash.throttle');
96
97
// Throttle scroll events to improve performance
98
var onScroll = throttle(function() {
99
console.log('Scroll event processed');
100
}, 100);
101
102
window.addEventListener('scroll', onScroll);
103
104
// Throttle API calls - only leading edge execution
105
var saveData = throttle(function(data) {
106
api.save(data);
107
}, 1000, { trailing: false });
108
109
// Throttle with both leading and trailing execution (default behavior)
110
var updatePosition = throttle(function(x, y) {
111
element.style.left = x + 'px';
112
element.style.top = y + 'px';
113
}, 50);
114
```
115
116
### Cancel Method
117
118
Cancels delayed function invocations.
119
120
```javascript { .api }
121
/**
122
* Cancels delayed function invocations
123
* @returns {void}
124
*/
125
throttledFunction.cancel();
126
```
127
128
The `cancel` method is attached to every throttled function returned by `throttle()`. It clears any pending invocations that would have been executed on the trailing edge.
129
130
**Usage Example:**
131
132
```javascript
133
var throttled = throttle(expensiveOperation, 1000);
134
135
// Queue some calls
136
throttled();
137
throttled();
138
139
// Cancel any pending trailing execution
140
throttled.cancel();
141
```
142
143
### Flush Method
144
145
Immediately invokes pending function invocations.
146
147
```javascript { .api }
148
/**
149
* Immediately invokes pending function invocations
150
* @returns {*} Returns the result of the last func invocation
151
*/
152
throttledFunction.flush();
153
```
154
155
The `flush` method is attached to every throttled function returned by `throttle()`. It immediately executes any pending invocation that would have been executed on the trailing edge.
156
157
**Usage Example:**
158
159
```javascript
160
var result;
161
var throttled = throttle(function(value) {
162
result = value * 2;
163
return result;
164
}, 1000);
165
166
throttled(5);
167
throttled(10);
168
169
// Immediately execute with the last arguments (10)
170
var flushResult = throttled.flush();
171
console.log(flushResult); // 20
172
console.log(result); // 20
173
```
174
175
## Types
176
177
```javascript { .api }
178
/**
179
* Options object for throttle function
180
*/
181
interface ThrottleOptions {
182
/** Specify invoking on the leading edge of the timeout */
183
leading?: boolean;
184
/** Specify invoking on the trailing edge of the timeout */
185
trailing?: boolean;
186
}
187
188
/**
189
* Throttled function with cancel and flush methods
190
*/
191
interface ThrottledFunction<T extends (...args: any[]) => any> {
192
/** Call the throttled function */
193
(...args: Parameters<T>): ReturnType<T>;
194
/** Cancel delayed function invocations */
195
cancel(): void;
196
/** Immediately invoke pending function invocations */
197
flush(): ReturnType<T>;
198
}
199
```
200
201
## Error Handling
202
203
The throttle function throws a `TypeError` if the first argument is not a function:
204
205
```javascript
206
try {
207
var invalid = throttle('not a function', 100);
208
} catch (error) {
209
console.log(error.message); // "Expected a function"
210
}
211
```
212
213
## Performance Considerations
214
215
- **Leading vs Trailing**: Use `leading: true, trailing: false` for immediate response to user input
216
- **Trailing only**: Use `leading: false, trailing: true` for batching operations
217
- **Wait time**: Choose appropriate wait times based on use case:
218
- UI events (scroll, resize): 16-100ms
219
- API calls: 300-1000ms
220
- User input validation: 300-500ms
221
222
## Common Use Cases
223
224
```javascript
225
var throttle = require('lodash.throttle');
226
227
// 1. Scroll event optimization
228
var onScroll = throttle(function() {
229
updateScrollPosition();
230
}, 16); // ~60fps
231
232
// 2. Window resize handling
233
var onResize = throttle(function() {
234
recalculateLayout();
235
}, 100);
236
237
// 3. API request rate limiting
238
var searchAPI = throttle(function(query) {
239
fetch('/api/search?q=' + query)
240
.then(handleResults);
241
}, 300, { leading: false });
242
243
// 4. Mouse move tracking with immediate feedback
244
var onMouseMove = throttle(function(event) {
245
updateCursor(event.clientX, event.clientY);
246
}, 16, { trailing: false });
247
```