Skip to content

Add debounced update plugin #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions plugins/debounce-update.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Debounce the update and highlighting function
* https://medium.com/@jamischarles/what-is-debouncing-2505c0648ff1
*/
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();
this.delayMs = delayMs;
}
/* Runs before elements are added into a `code-input`; Params: codeInput element) */
beforeElementsAdded(codeInput) {
console.log(codeInput, "before elements added");
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
}