Skip to content

Commit 4be16d1

Browse files
committed
Rewrite readme, split example to file
1 parent 2363c71 commit 4be16d1

3 files changed

Lines changed: 28 additions & 222 deletions

File tree

README.md

Lines changed: 1 addition & 218 deletions
Original file line numberDiff line numberDiff line change
@@ -19,224 +19,7 @@ A simple, thread-safe debounce library for Go that delays function execution unt
1919
## Installation
2020

2121
```bash
22-
go get github.com/your-username/debounce
23-
```
24-
25-
## Quick Start
26-
27-
```go
28-
package main
29-
30-
import (
31-
"fmt"
32-
"time"
33-
"github.com/your-username/debounce"
34-
)
35-
36-
func main() {
37-
// Create a debounced function with 500ms delay
38-
debounced := debounce.New(500 * time.Millisecond)
39-
40-
// This will only execute once, after 500ms
41-
debounced(func() {
42-
fmt.Println("Hello, World!")
43-
})
44-
45-
debounced(func() {
46-
fmt.Println("This will be executed instead")
47-
})
48-
49-
// Wait for execution
50-
time.Sleep(1 * time.Second)
51-
}
52-
```
53-
54-
## Usage
55-
56-
### Basic Debouncing
57-
58-
```go
59-
debounced := debounce.New(200 * time.Millisecond)
60-
61-
// Rapid calls - only the last one executes
62-
for i := 0; i < 10; i++ {
63-
debounced(func() {
64-
fmt.Printf("Executed at %v\n", time.Now())
65-
})
66-
time.Sleep(50 * time.Millisecond) // Less than debounce duration
67-
}
68-
```
69-
70-
### Call Limit
71-
72-
Execute immediately after a specified number of calls:
73-
74-
```go
75-
debounced := debounce.New(
76-
1*time.Second,
77-
debounce.WithMaxCalls(5),
78-
)
79-
80-
// Will execute immediately after 5 calls
81-
for i := 0; i < 10; i++ {
82-
debounced(func() {
83-
fmt.Printf("Executed after %d calls\n", i+1)
84-
})
85-
}
86-
```
87-
88-
### Time Limit
89-
90-
Execute immediately after a maximum wait time, regardless of debounce duration:
91-
92-
```go
93-
debounced := debounce.New(
94-
10*time.Second, // Long debounce duration
95-
debounce.WithMaxWait(2*time.Second), // But execute after 2 seconds max
96-
)
97-
98-
// Will execute after 2 seconds, not 10
99-
debounced(func() {
100-
fmt.Println("Executed due to time limit")
101-
})
102-
```
103-
104-
### Combined Limits
105-
106-
```go
107-
debounced := debounce.New(
108-
5*time.Second,
109-
debounce.WithMaxCalls(3),
110-
debounce.WithMaxWait(2*time.Second),
111-
)
112-
113-
// Executes when either:
114-
// - 3 calls are made, OR
115-
// - 2 seconds have passed, OR
116-
// - 5 seconds pass without new calls
117-
```
118-
119-
### Real-World Example: Search Input
120-
121-
```go
122-
package main
123-
124-
import (
125-
"fmt"
126-
"time"
127-
"github.com/your-username/debounce"
128-
)
129-
130-
func searchAPI(query string) {
131-
fmt.Printf("Searching for: %s\n", query)
132-
// Simulate API call
133-
}
134-
135-
func main() {
136-
// Debounce search to avoid excessive API calls
137-
debouncedSearch := debounce.New(300 * time.Millisecond)
138-
139-
// Simulate rapid user typing
140-
queries := []string{"h", "he", "hel", "hell", "hello", "hello world"}
141-
142-
for _, query := range queries {
143-
// Capture query in closure
144-
q := query
145-
debouncedSearch(func() {
146-
searchAPI(q)
147-
})
148-
time.Sleep(100 * time.Millisecond) // Simulate typing speed
149-
}
150-
151-
// Wait for final search
152-
time.Sleep(500 * time.Millisecond)
153-
// Output: Searching for: hello world
154-
}
155-
```
156-
157-
## API Reference
158-
159-
### `New(after time.Duration, options ...Option) func(f func())`
160-
161-
Creates a new debounced function.
162-
163-
**Parameters:**
164-
- `after`: Duration to wait before executing the function
165-
- `options`: Optional configuration options
166-
167-
**Returns:** A debounced function that accepts a function to execute
168-
169-
### Options
170-
171-
#### `WithMaxCalls(count int) Option`
172-
173-
Sets the maximum number of calls before immediate execution.
174-
175-
- `count`: Maximum number of calls (use -1 for no limit)
176-
- Default: No limit (-1)
177-
178-
#### `WithMaxWait(limit time.Duration) Option`
179-
180-
Sets the maximum wait time before immediate execution.
181-
182-
- `limit`: Maximum duration to wait
183-
- Default: No limit
184-
185-
## Behavior
186-
187-
### Function Selection
188-
When multiple calls are made quickly, only the **last** function provided will be executed:
189-
190-
```go
191-
debounced := debounce.New(100 * time.Millisecond)
192-
193-
debounced(func() { fmt.Println("First") })
194-
debounced(func() { fmt.Println("Second") })
195-
debounced(func() { fmt.Println("Third") })
196-
197-
// Output: Third
198-
```
199-
200-
### Execution Conditions
201-
The debounced function executes immediately when any of these conditions are met:
202-
203-
1. **Call limit reached**: Number of calls >= `WithMaxCalls` value
204-
2. **Time limit reached**: Time elapsed >= `WithMaxWait` value
205-
3. **Natural debounce**: No new calls for the specified `after` duration
206-
207-
### Reset Behavior
208-
After execution, all counters and timers are reset:
209-
210-
```go
211-
debounced := debounce.New(100*time.Millisecond, debounce.WithMaxCalls(2))
212-
213-
// First batch
214-
debounced(func() { fmt.Println("First execution") })
215-
debounced(func() { fmt.Println("First execution") }) // Executes immediately
216-
217-
// Second batch - counters are reset
218-
debounced(func() { fmt.Println("Second execution") })
219-
debounced(func() { fmt.Println("Second execution") }) // Executes immediately again
220-
```
221-
222-
## Thread Safety
223-
224-
This library is fully thread-safe and can be used safely across multiple goroutines:
225-
226-
```go
227-
debounced := debounce.New(100 * time.Millisecond)
228-
229-
var wg sync.WaitGroup
230-
for i := 0; i < 100; i++ {
231-
wg.Add(1)
232-
go func(id int) {
233-
defer wg.Done()
234-
debounced(func() {
235-
fmt.Printf("Executed from goroutine %d\n", id)
236-
})
237-
}(i)
238-
}
239-
wg.Wait()
22+
go get github.com/floatdrop/debounce
24023
```
24124

24225
## Use Cases

debounce.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@
44
// Use of this source code is governed by an MIT-style
55
// license that can be found in the LICENSE file.
66

7-
// A simple, thread-safe debounce library for Go that delays function execution until
8-
// after a specified duration has elapsed since the last invocation.
9-
// Perfect for rate limiting, reducing redundant operations, and
10-
// optimizing performance in high-frequency scenarios.
7+
// Package debounce provides a debouncer func.
118
package debounce
129

1310
import (

example_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package debounce_test
2+
3+
import (
4+
"fmt"
5+
"time"
6+
7+
"github.com/floatdrop/debounce"
8+
)
9+
10+
func ExampleNew() {
11+
// Create a debounced function with 500ms delay
12+
debounced := debounce.New(500 * time.Millisecond)
13+
14+
// This will only execute once, after 500ms
15+
debounced(func() {
16+
fmt.Println("Hello, World!")
17+
})
18+
19+
debounced(func() {
20+
fmt.Println("This will be executed instead")
21+
})
22+
23+
// Wait for execution
24+
time.Sleep(1 * time.Second)
25+
// Output: This will be executed instead
26+
}

0 commit comments

Comments
 (0)