Skip to content

Commit

Permalink
Merge pull request #26 from penge/debounce
Browse files Browse the repository at this point in the history
Optimize text save with debounce and beforeunload
  • Loading branch information
penge authored Nov 30, 2019
2 parents 33b225f + bef71fd commit fd0f1d8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"manifest_version": 2,
"name": "My Notes",
"description": "Chrome Extension that turns your \"New Tab\" into a note taking tool.",
"version": "1.3",
"version": "1.4",
"icons": { "128": "icon128.png" },
"options_page": "options.html",
"permissions": ["storage"],
Expand Down
49 changes: 42 additions & 7 deletions notes.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,13 @@ mode.addEventListener("click", function () {

/* Storage */

let lastSavedText;
let mostRecentValue;
let mostRecentSavedValue;

chrome.storage.sync.get(["value", "size", "font", "mode"], result => {
textarea.value = result.value || "";
lastSavedText = textarea.value;
mostRecentValue = textarea.value;
mostRecentSavedValue = textarea.value;

textarea.style.fontSize = (result.size || defaultSize) + "%";
textarea.style.fontFamily = result.font.fontFamily;
Expand All @@ -95,6 +97,39 @@ function isShift(event) {
return event.shiftKey;
}

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

function saveText() {
if (mostRecentValue === mostRecentSavedValue) {
return;
}

const value = textarea.value;
chrome.storage.sync.set({ value: value }, function () {
mostRecentSavedValue = value;
});
}

const saveTextDebounce = debounce(saveText, 1000, true);

textarea.addEventListener("keydown", (event) => {
if (isTab(event)) {
event.preventDefault();
Expand Down Expand Up @@ -139,15 +174,15 @@ textarea.addEventListener("keyup", (event) => {
}

// Do not save text if unchanged (Ctrl, Alt, Shift, Arrow keys)
if (lastSavedText === textarea.value) {
if (mostRecentValue === textarea.value) {
return;
}

chrome.storage.sync.set({ value: textarea.value }, function () {
lastSavedText = textarea.value;
});

mostRecentValue = textarea.value;
setPlaceholder();
saveTextDebounce();
});

window.addEventListener("beforeunload", saveText);

})(); // IIFE

0 comments on commit fd0f1d8

Please sign in to comment.