or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Throttle Debounce

1

2

Throttle Debounce provides high-performance throttle and debounce utility functions for JavaScript applications. It offers both throttling (rate-limiting function execution to occur at most once per specified time interval) and debouncing (delaying function execution until after specified time has elapsed since the last invocation) with flexible configuration options.

3

4

## Package Information

5

6

- **Package Name**: throttle-debounce

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES modules and CommonJS support)

9

- **Installation**: `npm install throttle-debounce`

10

11

## Core Imports

12

13

```javascript

14

import { throttle, debounce } from "throttle-debounce";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { throttle, debounce } = require("throttle-debounce");

21

```

22

23

Individual imports (direct from source files):

24

25

```javascript

26

import throttle from "throttle-debounce/throttle.js";

27

import debounce from "throttle-debounce/debounce.js";

28

```

29

30

## Basic Usage

31

32

```javascript

33

import { throttle, debounce } from "throttle-debounce";

34

35

// Throttle: Limit function execution to once per time period

36

const throttleFunc = throttle(1000, (num) => {

37

console.log("throttled:", num);

38

});

39

40

throttleFunc(1); // Executes immediately

41

throttleFunc(2); // Ignored

42

throttleFunc(3); // Ignored

43

// Final call will execute after 1000ms if noTrailing is false

44

45

// Debounce: Delay execution until calls stop coming

46

const debounceFunc = debounce(1000, (num) => {

47

console.log("debounced:", num);

48

});

49

50

debounceFunc(1); // Won't execute

51

debounceFunc(2); // Won't execute

52

debounceFunc(3); // Will execute after 1000ms of no more calls

53

```

54

55

## Architecture

56

57

Throttle Debounce is built around a shared throttling mechanism:

58

59

- **Throttle Function**: Core implementation using `setTimeout`/`clearTimeout` for timing control

60

- **Debounce Function**: Wrapper around throttle with specific `debounceMode` configuration

61

- **Cancellation System**: Both functions support cancelling pending executions via `.cancel()` method

62

- **Context Preservation**: Preserves the original function's `this` context and all arguments using `.apply()`, ensuring the callback executes with the same context as the wrapper function was called

63

- **State Management**: Tracks execution timing and cancellation state internally

64

65

## Capabilities

66

67

### Throttling

68

69

Rate-limits function execution to occur at most once per specified time interval, useful for event handlers on scroll, resize, or other high-frequency events.

70

71

```javascript { .api }

72

/**

73

* Throttle execution of a function

74

* @param {number} delay - Zero-or-greater delay in milliseconds

75

* @param {Function} callback - Function to be executed after delay

76

* @param {Object} [options] - Configuration options

77

* @param {boolean} [options.noTrailing=false] - Skip final execution after calls stop

78

* @param {boolean} [options.noLeading=false] - Skip immediate execution on first call

79

* @param {boolean} [options.debounceMode] - Internal parameter for debounce mode

80

* @returns {Function} Throttled wrapper function with cancel method

81

*/

82

function throttle(delay, callback, options);

83

```

84

85

**Usage Examples:**

86

87

```javascript

88

import { throttle } from "throttle-debounce";

89

90

// Basic throttling - executes immediately and after delay

91

const basicThrottle = throttle(250, () => {

92

console.log("Throttled execution");

93

});

94

95

// No leading execution - skip immediate execution

96

const noLeadingThrottle = throttle(250, handleScroll, {

97

noLeading: true

98

});

99

100

// No trailing execution - skip final execution

101

const noTrailingThrottle = throttle(250, handleResize, {

102

noTrailing: true

103

});

104

105

// Event handler example

106

window.addEventListener("scroll", throttle(100, () => {

107

console.log("Scroll position:", window.scrollY);

108

}));

109

```

110

111

### Debouncing

112

113

Delays function execution until after specified time has elapsed since the last invocation, ensuring function executes only once after a series of rapid calls.

114

115

```javascript { .api }

116

/**

117

* Debounce execution of a function

118

* @param {number} delay - Zero-or-greater delay in milliseconds

119

* @param {Function} callback - Function to be executed after delay

120

* @param {Object} [options] - Configuration options

121

* @param {boolean} [options.atBegin=false] - Execute at beginning vs end of calls

122

* @returns {Function} Debounced wrapper function with cancel method

123

*/

124

function debounce(delay, callback, options);

125

```

126

127

**Usage Examples:**

128

129

```javascript

130

import { debounce } from "throttle-debounce";

131

132

// Basic debouncing - executes after calls stop

133

const searchDebounce = debounce(300, (query) => {

134

performSearch(query);

135

});

136

137

// Execute at beginning of call series

138

const saveDebounce = debounce(1000, saveData, {

139

atBegin: true

140

});

141

142

// Input field example

143

document.getElementById("search").addEventListener("input",

144

debounce(300, (event) => {

145

console.log("Search for:", event.target.value);

146

})

147

);

148

```

149

150

### Cancellation

151

152

Both throttled and debounced functions support cancelling pending executions.

153

154

```javascript { .api }

155

/**

156

* Cancel pending function executions and optionally prevent future executions

157

* @param {Object} [options] - Cancel configuration

158

* @param {boolean} [options.upcomingOnly=false] - If false (default), cancels all pending executions and prevents future ones until function is called again. If true, cancels only the next scheduled execution while allowing future executions to proceed normally.

159

*/

160

throttledFunction.cancel(options);

161

debouncedFunction.cancel(options);

162

```

163

164

**Usage Examples:**

165

166

```javascript

167

const throttleFunc = throttle(1000, handleEvent);

168

const debounceFunc = debounce(1000, handleInput);

169

170

// Cancel all pending and future executions

171

// Clears any pending timeout and sets internal cancelled flag

172

throttleFunc.cancel();

173

debounceFunc.cancel();

174

175

// Cancel only the next scheduled execution

176

// Clears pending timeout but allows future calls to work normally

177

debounceFunc.cancel({ upcomingOnly: true });

178

179

// Component cleanup example with context preservation

180

class MyComponent {

181

constructor() {

182

// Context is automatically preserved - no need for .bind()

183

this.handleScroll = throttle(100, this.onScroll);

184

}

185

186

onScroll() {

187

// 'this' refers to MyComponent instance

188

console.log('Scrolling in component:', this.constructor.name);

189

}

190

191

destroy() {

192

this.handleScroll.cancel(); // Clean up pending executions

193

}

194

}

195

```

196

197

## Types

198

199

```javascript { .api }

200

// Throttle options

201

interface ThrottleOptions {

202

/** Skip final execution after calls stop */

203

noTrailing?: boolean;

204

/** Skip immediate execution on first call */

205

noLeading?: boolean;

206

/** Internal parameter for debounce mode */

207

debounceMode?: boolean;

208

}

209

210

// Debounce options

211

interface DebounceOptions {

212

/** Execute at beginning vs end of calls */

213

atBegin?: boolean;

214

}

215

216

// Cancel options

217

interface CancelOptions {

218

/** Cancel only next execution, not all future ones */

219

upcomingOnly?: boolean;

220

}

221

222

// Throttled/Debounced function interface

223

interface ThrottledFunction extends Function {

224

/** Cancel pending executions */

225

cancel(options?: CancelOptions): void;

226

}

227

```