-
Notifications
You must be signed in to change notification settings - Fork 37
/
debounce.ts
80 lines (74 loc) · 2.38 KB
/
debounce.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { tracked } from '@glimmer/tracking';
import { resource } from '../core';
class TrackedValue<T> {
@tracked value: T | undefined;
}
/**
* <div class="callout note">
*
* This is not a core part of ember-resources, but is an example utility to demonstrate a concept when authoring your own resources. However, this utility is still under the broader library's SemVer policy.
*
* A consuming app will not pay for the bytes of this utility unless imported.
*
* </div>
*
* A utility for debouncing high-frequency updates.
* The returned value will only be updated every `ms` and is
* initially undefined.
*
* This can be useful when a user's typing is updating a tracked
* property and you want to derive data less frequently than on
* each keystroke.
*
* Note that this utility requires the `@use` decorator
* (debounce could be implemented without the need for the `@use` decorator
* but the current implementation is 8 lines)
*
* @example
* ```js
* import Component from '@glimmer/component';
* import { tracked } from '@glimmer/tracking';
* import { debounce } from 'ember-resources/util/debounce';
*
* const delay = 100; // ms
*
* class Demo extends Component {
* @tracked userInput = '';
*
* @use debouncedInput = debounce(delay, () => this.userInput);
* }
* ```
*
* @example
* This could be further composed with RemoteData
* ```js
* import Component from '@glimmer/component';
* import { tracked } from '@glimmer/tracking';
* import { debounce } from 'ember-resources/util/debounce';
* import { RemoteData } from 'ember-resources/util/remote-data';
*
* const delay = 100; // ms
*
* class Demo extends Component {
* @tracked userInput = '';
*
* @use debouncedInput = debounce(delay, () => this.userInput);
*
* @use search = RemoteData(() => `https://my.domain/search?q=${this.debouncedInput}`);
* }
* ```
*
* @param {number} ms delay in milliseconds to wait before updating the returned value
* @param {() => Value} thunk function that returns the value to debounce
*/
export function debounce<Value = unknown>(ms: number, thunk: () => Value) {
let lastValue: Value;
let timer: number;
let state = new TrackedValue<Value>();
return resource(({ on }) => {
lastValue = thunk();
on.cleanup(() => timer && clearTimeout(timer));
timer = setTimeout(() => (state.value = lastValue), ms);
return state.value;
});
}