Skip to content

Commit 3ef3ca4

Browse files
committed
Add debounced update plugin
1 parent eeddb43 commit 3ef3ca4

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

plugins/debounce-update.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Debounce the update and highlighting function
3+
* https://medium.com/@jamischarles/what-is-debouncing-2505c0648ff1
4+
*/
5+
codeInput.plugins.DebounceUpdate = class extends codeInput.Plugin {
6+
/**
7+
* Create a debounced update plugin to pass into a template
8+
* @param {Number} delayMs Delay, in ms, to wait until updating the syntax highlighting
9+
*/
10+
constructor(delayMs) {
11+
super();
12+
this.delayMs = delayMs;
13+
}
14+
/* Runs before elements are added into a `code-input`; Params: codeInput element) */
15+
beforeElementsAdded(codeInput) {
16+
console.log(codeInput, "before elements added");
17+
this.update = codeInput.update.bind(codeInput); // Save previous update func
18+
codeInput.update = this.updateDebounced.bind(this, codeInput);
19+
}
20+
21+
/**
22+
* Debounce the `update` function
23+
*/
24+
updateDebounced(codeInput, text) {
25+
// Editing - cancel prev. timeout
26+
if(this.debounceTimeout != null) {
27+
window.clearTimeout(this.debounceTimeout);
28+
}
29+
30+
this.debounceTimeout = window.setTimeout(() => {
31+
// Closure arrow function can take in variables like `text`
32+
this.update(text);
33+
}, this.delayMs);
34+
}
35+
36+
// this.`update` function is original function
37+
38+
debounceTimeout = null; // Timeout until update
39+
delayMs = 0; // Time until update
40+
}

0 commit comments

Comments
 (0)