Skip to content

Commit d6301aa

Browse files
committed
Switch to throttle instead of debounce
debounce waits for a lull in activity, whereas throttle will simply coalesce multiple calls into "one" per time period. This may result in more requests, but it will also result in data being saved even when the user is actively entering it.
1 parent 7cbed72 commit d6301aa

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

app/assets/javascripts/drafts.js

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
$(function() {
2+
// The main function that serializes the form and sends it to the save draft endpoint.
3+
//
4+
// It is wrapped in _.throttle so it is called on the trailing edge at most
5+
// once in a 3 second window. More casually this means no matter how many
6+
// times the function is called within a 3 second window, the code will only
7+
// actually be executed once at the end of the window.
8+
//
9+
// The draft is therefore saved periodically and after things have "settled,"
10+
// but not so often as to flood the server with requests.
211
var currentDraftRequest;
3-
const saveDraftDebounced = _.debounce(function(e) {
12+
const saveDraftThrottled = _.throttle(function(e) {
413
let $target = $(e.target);
514
let $form = $target.closest("form");
615
let draftsURL = $form.data("drafts-url");
@@ -36,21 +45,17 @@ $(function() {
3645

3746
$form.trigger("draft:error", [jqXHR, textStatus, errorThrown]);
3847

39-
// Retry. Rely on debounce to coalesce multiple calls into one retry.
40-
saveDraftDebounced(e);
48+
// Retry. Rely on throttle to coalesce multiple calls into one retry.
49+
saveDraftThrottled(e);
4150
},
4251
});
43-
}, 2500);
52+
}, 3000, { leading: false });
4453

54+
// Save drafts for forms where data-drafts-url is present as an attribute.
4555
const $formsWithDraftsURLs = $("form[data-drafts-url]");
46-
$formsWithDraftsURLs.on("blur change", ":input", saveDraftDebounced)
47-
48-
// After the draft is discarded, reload the page to empty out all fields and
49-
// start from scratch cleanly.
50-
$("a.discard-draft-link").on("ajax:complete", function(e) {
51-
location.reload(true);
52-
});
56+
$formsWithDraftsURLs.on("blur change", ":input", saveDraftThrottled)
5357

58+
// Trigger validation and cursor restoration for draft-enabled forms
5459
$formsWithDraftsURLs.each(function() {
5560
const $form = $(this);
5661
if ($form.data("draft-restored")) {
@@ -60,4 +65,10 @@ $(function() {
6065
$("#" + $form.data("draft-focused-dom-id")).focus();
6166
}
6267
});
68+
69+
// After the draft is discarded, reload the page to empty out all fields and
70+
// start from scratch cleanly.
71+
$("a.discard-draft-link").on("ajax:complete", function(e) {
72+
location.reload(true);
73+
});
6374
});

0 commit comments

Comments
 (0)