debounce-ts 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Atif C
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # debounce-ts
2
+
3
+ A lightweight, type-safe debounce utility for both sync and async functions with support for leading-edge execution, maximum wait enforcement, and error handling.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install debounce-ts
9
+ ```
10
+
11
+ ## Basic Usage
12
+
13
+ ```typescript
14
+ import { debounce } from 'debounce-ts';
15
+
16
+ // Async function example
17
+ const saveData = debounce(
18
+ async (text: string) => {
19
+ await fetch('/api/save', {
20
+ method: 'POST',
21
+ body: JSON.stringify({ text })
22
+ });
23
+ },
24
+ { delay: 500 }
25
+ );
26
+
27
+ // Fire-and-forget — function is invoked 500ms after last call
28
+ input.addEventListener('input', e => saveData(e.target.value));
29
+
30
+ // Sync function example
31
+ const updateCounter = debounce(
32
+ (count: number) => {
33
+ document.getElementById('counter').textContent = count.toString();
34
+ },
35
+ { delay: 300 }
36
+ );
37
+
38
+ button.addEventListener('click', () => updateCounter(++clicks));
39
+ ```
40
+
41
+ ## API
42
+
43
+ ### debounce(fn, options?)
44
+
45
+ **Parameters:**
46
+
47
+ - `fn` (Function): Function to debounce (can be sync or async)
48
+ - `options` (object, optional):
49
+ - `immediate` (boolean, default: `false`) — Fire on leading edge. Also fires trailing if new args arrive during cooldown.
50
+ - `delay` (number, default: `1000`) — Wait time in ms after last call
51
+ - `maxWait` (number, optional) — Max time before forced execution
52
+ - `onError` ((error: unknown) => void, optional) — Error handler for async rejections. Without this, errors surface as unhandled rejections.
53
+
54
+ **Returns:** `DebouncedFunction` — Debounced function (void return, fire-and-forget)
55
+
56
+ **Methods on returned function:**
57
+
58
+ - `.cancel()` — Cancel all pending invocations and clear timers
59
+ - `.flush()` — Immediately execute pending invocation (if any) and clear timers
60
+
61
+ **Throws:**
62
+
63
+ - `TypeError` if delay is not a non-negative number
64
+ - `TypeError` if maxWait is not a non-negative number
65
+ - `TypeError` if maxWait < delay
66
+
67
+ ## Comprehensive Example
68
+
69
+ ```typescript
70
+ import { debounce } from 'debounce-ts';
71
+
72
+ // Real-world: Auto-save user input
73
+ // - Immediate feedback (save on first keystroke)
74
+ // - Debounced API calls (wait 500ms after typing stops)
75
+ // - Maximum 5-second delay (force-save during continuous typing)
76
+ // - Error handling via onError callback
77
+
78
+ const autoSave = debounce(
79
+ async (text: string) => {
80
+ const response = await fetch('/api/save', {
81
+ method: 'POST',
82
+ body: JSON.stringify({ text })
83
+ });
84
+ if (!response.ok) throw new Error('Save failed');
85
+ },
86
+ {
87
+ immediate: true,
88
+ delay: 500,
89
+ maxWait: 5000,
90
+ onError: error => {
91
+ console.error('Auto-save failed:', error);
92
+ showNotification('Failed to save. Will retry...');
93
+ }
94
+ }
95
+ );
96
+
97
+ // Fire-and-forget — errors route to onError callback
98
+ const textInput = document.querySelector('textarea');
99
+ textInput.addEventListener('input', e => {
100
+ autoSave(e.target.value);
101
+ });
102
+
103
+ // Force-save any pending data before page unload
104
+ window.addEventListener('beforeunload', () => {
105
+ autoSave.flush();
106
+ });
107
+
108
+ // Cancel pending save (e.g., user discards changes)
109
+ function handleDiscard() {
110
+ autoSave.cancel();
111
+ }
112
+ ```
113
+
114
+ ## Error Handling
115
+
116
+ By default, errors from the debounced function (both sync and async) surface as **unhandled rejections** (Node's standard behavior). To handle errors explicitly:
117
+
118
+ ```typescript
119
+ const save = debounce(
120
+ async data => {
121
+ throw new Error('Network error');
122
+ },
123
+ {
124
+ onError: error => {
125
+ // Handle error here
126
+ console.error('Save failed:', error);
127
+ }
128
+ }
129
+ );
130
+ ```
131
+
132
+ Without `onError`, the error will trigger Node's `unhandledRejection` event, making it visible in logs and crash reporters.
133
+
134
+ ## TypeScript Support
135
+
136
+ This package is written in TypeScript and exports full type definitions. The `DebouncedFunction` interface is exported for use in your code:
137
+
138
+ ```typescript
139
+ import { debounce, DebouncedFunction } from 'debounce-ts';
140
+
141
+ const save: DebouncedFunction<[string]> = debounce(
142
+ async (text: string) => {
143
+ await api.save(text);
144
+ },
145
+ { delay: 500 }
146
+ );
147
+ ```
148
+
149
+ ## License
150
+
151
+ MIT
@@ -0,0 +1,61 @@
1
+ export interface DebounceOptions {
2
+ immediate?: boolean;
3
+ delay?: number;
4
+ maxWait?: number;
5
+ onError?: (error: unknown) => void;
6
+ }
7
+ export interface DebouncedFunction<TArgs extends readonly unknown[]> {
8
+ (...args: TArgs): void;
9
+ cancel(): void;
10
+ flush(): void;
11
+ }
12
+ /**
13
+ * Creates a debounced version of a function (sync or async) that delays invoking it
14
+ * until after a specified wait time has elapsed since the last call.
15
+ *
16
+ * Supports leading-edge invocation (immediate), max wait enforcement, and
17
+ * error handling via an onError callback.
18
+ *
19
+ * @template TArgs - Function argument types
20
+ * @template TReturn - Function return type
21
+ * @param {Function} fn - Function to debounce (can be sync or async)
22
+ * @param {DebounceOptions} [options] - Configuration options
23
+ * @param {boolean} [options.immediate=false] - Fire on leading edge. Also fires
24
+ * trailing if new args arrive during cooldown.
25
+ * @param {number} [options.delay=1000] - Delay in ms after last call
26
+ * @param {number} [options.maxWait] - Max time in ms before forced execution
27
+ * @param {Function} [options.onError] - Error handler for async rejections.
28
+ * Without this, errors surface as unhandled rejections.
29
+ * @returns {DebouncedFunction} Debounced function (void return) with
30
+ * cancel() and flush() methods
31
+ *
32
+ * @throws {TypeError} If delay is not a non-negative number
33
+ * @throws {TypeError} If maxWait is not a non-negative number
34
+ * @throws {TypeError} If maxWait < delay
35
+ *
36
+ * @example
37
+ * // Async function
38
+ * const save = debounce(async (data) => {
39
+ * await api.save(data);
40
+ * }, {
41
+ * delay: 500,
42
+ * maxWait: 5000,
43
+ * immediate: true,
44
+ * onError: (err) => console.error('Save failed:', err),
45
+ * });
46
+ *
47
+ * // Sync function
48
+ * const updateUI = debounce((value) => {
49
+ * element.textContent = value;
50
+ * }, { delay: 300 });
51
+ *
52
+ * input.addEventListener('input', (e) => save(e.target.value));
53
+ *
54
+ * // Cleanup on unmount:
55
+ * save.cancel();
56
+ *
57
+ * // Force save before navigation:
58
+ * save.flush();
59
+ */
60
+ export declare const debounce: <TArgs extends readonly unknown[], TReturn>(fn: (...args: TArgs) => TReturn | Promise<TReturn>, options?: DebounceOptions) => DebouncedFunction<TArgs>;
61
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,eAAe;IAC/B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,iBAAiB,CAAC,KAAK,SAAS,SAAS,OAAO,EAAE;IAClE,CAAC,GAAG,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACvB,MAAM,IAAI,IAAI,CAAC;IACf,KAAK,IAAI,IAAI,CAAC;CACd;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,SAAS,SAAS,OAAO,EAAE,EAAE,OAAO,EACjE,IAAI,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,EAClD,UAAU,eAAe,KACvB,iBAAiB,CAAC,KAAK,CA4HzB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Creates a debounced version of a function (sync or async) that delays invoking it
3
+ * until after a specified wait time has elapsed since the last call.
4
+ *
5
+ * Supports leading-edge invocation (immediate), max wait enforcement, and
6
+ * error handling via an onError callback.
7
+ *
8
+ * @template TArgs - Function argument types
9
+ * @template TReturn - Function return type
10
+ * @param {Function} fn - Function to debounce (can be sync or async)
11
+ * @param {DebounceOptions} [options] - Configuration options
12
+ * @param {boolean} [options.immediate=false] - Fire on leading edge. Also fires
13
+ * trailing if new args arrive during cooldown.
14
+ * @param {number} [options.delay=1000] - Delay in ms after last call
15
+ * @param {number} [options.maxWait] - Max time in ms before forced execution
16
+ * @param {Function} [options.onError] - Error handler for async rejections.
17
+ * Without this, errors surface as unhandled rejections.
18
+ * @returns {DebouncedFunction} Debounced function (void return) with
19
+ * cancel() and flush() methods
20
+ *
21
+ * @throws {TypeError} If delay is not a non-negative number
22
+ * @throws {TypeError} If maxWait is not a non-negative number
23
+ * @throws {TypeError} If maxWait < delay
24
+ *
25
+ * @example
26
+ * // Async function
27
+ * const save = debounce(async (data) => {
28
+ * await api.save(data);
29
+ * }, {
30
+ * delay: 500,
31
+ * maxWait: 5000,
32
+ * immediate: true,
33
+ * onError: (err) => console.error('Save failed:', err),
34
+ * });
35
+ *
36
+ * // Sync function
37
+ * const updateUI = debounce((value) => {
38
+ * element.textContent = value;
39
+ * }, { delay: 300 });
40
+ *
41
+ * input.addEventListener('input', (e) => save(e.target.value));
42
+ *
43
+ * // Cleanup on unmount:
44
+ * save.cancel();
45
+ *
46
+ * // Force save before navigation:
47
+ * save.flush();
48
+ */
49
+ export const debounce = (fn, options) => {
50
+ const { immediate = false, delay = 1000, maxWait, onError } = options ?? {};
51
+ // Input validation
52
+ if (typeof delay !== 'number' || Number.isNaN(delay) || delay < 0) {
53
+ throw new TypeError('delay must be a non-negative number');
54
+ }
55
+ if (maxWait !== undefined) {
56
+ if (typeof maxWait !== 'number' || Number.isNaN(maxWait) || maxWait < 0) {
57
+ throw new TypeError('maxWait must be a non-negative number');
58
+ }
59
+ if (maxWait < delay) {
60
+ throw new TypeError('maxWait must be greater than or equal to delay');
61
+ }
62
+ }
63
+ let timeout = null;
64
+ let maxTimeout = null;
65
+ let pendingArgs = null;
66
+ let firstCallTime = null;
67
+ const invoke = () => {
68
+ if (!pendingArgs)
69
+ return;
70
+ const args = pendingArgs;
71
+ pendingArgs = null;
72
+ // Wrap in try-catch to handle sync errors, then Promise.resolve() for async
73
+ try {
74
+ const result = fn(...args);
75
+ const promise = Promise.resolve(result);
76
+ if (onError) {
77
+ promise.catch(onError);
78
+ }
79
+ // Without onError, the rejection is unhandled → triggers
80
+ // Node's unhandledRejection event (standard, visible behavior)
81
+ }
82
+ catch (error) {
83
+ // Handle synchronous errors
84
+ if (onError) {
85
+ onError(error);
86
+ }
87
+ else {
88
+ // Re-throw to maintain unhandled rejection behavior
89
+ Promise.reject(error);
90
+ }
91
+ }
92
+ };
93
+ const clearTimers = () => {
94
+ if (timeout) {
95
+ clearTimeout(timeout);
96
+ timeout = null;
97
+ }
98
+ if (maxTimeout) {
99
+ clearTimeout(maxTimeout);
100
+ maxTimeout = null;
101
+ }
102
+ };
103
+ const startMaxWaitTimer = () => {
104
+ if (maxWait === undefined || maxTimeout || firstCallTime === null)
105
+ return;
106
+ const elapsed = Date.now() - firstCallTime;
107
+ const remaining = Math.max(0, maxWait - elapsed);
108
+ maxTimeout = setTimeout(() => {
109
+ clearTimers();
110
+ invoke();
111
+ firstCallTime = null;
112
+ }, remaining);
113
+ };
114
+ const debounced = ((...args) => {
115
+ pendingArgs = args;
116
+ if (firstCallTime === null) {
117
+ firstCallTime = Date.now();
118
+ }
119
+ const shouldInvokeLeading = immediate && timeout === null;
120
+ if (timeout) {
121
+ clearTimeout(timeout);
122
+ }
123
+ timeout = setTimeout(() => {
124
+ timeout = null;
125
+ // Fire trailing call if:
126
+ // - Not in immediate mode (standard trailing behavior), OR
127
+ // - In immediate mode AND new args arrived after the leading call
128
+ if (!immediate || pendingArgs !== null) {
129
+ invoke();
130
+ }
131
+ if (maxTimeout) {
132
+ clearTimeout(maxTimeout);
133
+ maxTimeout = null;
134
+ }
135
+ firstCallTime = null;
136
+ }, delay);
137
+ if (shouldInvokeLeading) {
138
+ invoke();
139
+ // invoke() nulls pendingArgs. Any subsequent call during cooldown
140
+ // sets pendingArgs to new args, which the trailing timeout detects.
141
+ }
142
+ startMaxWaitTimer();
143
+ });
144
+ debounced.cancel = () => {
145
+ clearTimers();
146
+ pendingArgs = null;
147
+ firstCallTime = null;
148
+ };
149
+ debounced.flush = () => {
150
+ clearTimers();
151
+ invoke();
152
+ };
153
+ return debounced;
154
+ };
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "debounce-ts",
3
+ "version": "1.0.0",
4
+ "description": "Small and fast debounce function",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "sideEffects": false,
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "test": "vitest run",
21
+ "test:watch": "vitest --watch",
22
+ "test:coverage": "vitest run --coverage",
23
+ "prettier:check": "prettier --check .",
24
+ "prettier:write": "prettier --write .",
25
+ "elint:check": "eslint .",
26
+ "elint:fix": "eslint --fix .",
27
+ "format": "prettier --write . && eslint --fix .",
28
+ "type-check": "tsc --noEmit",
29
+ "prepublishOnly": "npm run build"
30
+ },
31
+ "keywords": [
32
+ "debounce",
33
+ "debouncing",
34
+ "function",
35
+ "throttle",
36
+ "invoke",
37
+ "limit",
38
+ "limited",
39
+ "interval",
40
+ "rate",
41
+ "batch",
42
+ "rate-limit",
43
+ "async",
44
+ "sync",
45
+ "typescript"
46
+ ],
47
+ "author": "Atif C <atifcdev@gmail.com>",
48
+ "license": "MIT",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/atif-c/debounce-ts.git"
52
+ },
53
+ "bugs": {
54
+ "url": "https://github.com/atif-c/debounce-ts/issues"
55
+ },
56
+ "homepage": "https://github.com/atif-c/debounce-ts#readme",
57
+ "devDependencies": {
58
+ "@eslint/js": "^9.18.0",
59
+ "@vitest/coverage-v8": "^2.1.8",
60
+ "eslint": "^9.18.0",
61
+ "prettier": "^3.4.2",
62
+ "typescript": "^5.9.3",
63
+ "typescript-eslint": "^8.19.1",
64
+ "vitest": "^2.1.8"
65
+ }
66
+ }