-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathdebounce-update.js
40 lines (36 loc) · 1.34 KB
/
debounce-update.js
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
/**
* Debounce the update and highlighting function
* https://medium.com/@jamischarles/what-is-debouncing-2505c0648ff1
* Files: debounce-update.js
*/
codeInput.plugins.DebounceUpdate = class extends codeInput.Plugin {
/**
* Create a debounced update plugin to pass into a template
* @param {Number} delayMs Delay, in ms, to wait until updating the syntax highlighting
*/
constructor(delayMs) {
super([]); // No observed attributes
this.delayMs = delayMs;
}
/* Runs before elements are added into a `code-input`; Params: codeInput element) */
beforeElementsAdded(codeInput) {
this.update = codeInput.update.bind(codeInput); // Save previous update func
codeInput.update = this.updateDebounced.bind(this, codeInput);
}
/**
* Debounce the `update` function
*/
updateDebounced(codeInput, text) {
// Editing - cancel prev. timeout
if(this.debounceTimeout != null) {
window.clearTimeout(this.debounceTimeout);
}
this.debounceTimeout = window.setTimeout(() => {
// Closure arrow function can take in variables like `text`
this.update(text);
}, this.delayMs);
}
// this.`update` function is original function
debounceTimeout = null; // Timeout until update
delayMs = 0; // Time until update
}