diff --git a/src/helpers.js b/src/helpers.js index 583ffa8..b05511f 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -33,6 +33,36 @@ function E(t){ return document.createElement(t); } +/** 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_ms, immediate) { + let timeout; + + return function() { + const context = this; + const args = arguments; + + const later = ()=> { + timeout = null; + if (!immediate) { + func.apply(context, args); + } + }; + + const callNow = immediate && !timeout; + + clearTimeout(timeout); + + timeout = setTimeout(later, wait_ms); + + if (callNow) { + func.apply(context, args); + } + }; +} + function memoize_synchronous_function(func) { const cache = {}; return (...args)=> { diff --git a/src/sessions.js b/src/sessions.js index 6546c44..25aa9d9 100644 --- a/src/sessions.js +++ b/src/sessions.js @@ -100,7 +100,7 @@ const lsid = `image#${session_id}`; log(`local storage id: ${lsid}`); // save image to storage - const save_image_to_storage = () => { + const save_image_to_storage = debounce(() => { const save_paused = handle_data_loss(); if (save_paused) { return; @@ -117,7 +117,7 @@ } } }); - }; + }, 100); storage.get(lsid, (err, uri) => { if (err) { if (localStorageAvailable) { @@ -331,7 +331,7 @@ }); let previous_uri; // let pointer_operations = []; // the multiplayer syncing stuff is a can of worms, so this is disabled - const write_canvas_to_database = () => { + const write_canvas_to_database = debounce(() => { const save_paused = handle_data_loss(); if (save_paused) { return; @@ -348,7 +348,7 @@ else { log("(don't write canvas data to Firebase; it hasn't changed)"); } - }; + }, 100); let ignore_session_update = false; $G.on("session-update.session-hook", ()=> { if (ignore_session_update) {