From 0ae30508da3b8902c78b07760e51f92bf9783d31 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Sun, 27 Nov 2022 14:58:40 +0100 Subject: Dynamic reload times to limit server load --- html/whiteboard.js | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/html/whiteboard.js b/html/whiteboard.js index 9018f92..d9f0904 100644 --- a/html/whiteboard.js +++ b/html/whiteboard.js @@ -3,6 +3,65 @@ function init() { init_board(); } +class AdjustingTimer { + constructor() { + this.update_counter = 0; // counting seconds since last counter reset + } + + fast_mode() { + if (this.update_counter < 5*60) + return true; + return false; + } + + // private method + // returns current interval in ms + current_update_interval() + { + if (this.fast_mode()) + return 2000; // 2s + else + return 5 * 60000; // 5min + }; + + // private + count() { + this.update_counter += this.current_update_interval() / 1000; + }; + + // private + on_timeout() { + this.m_fn(); + this.count(); + var _this = this; + this.update_timer = setTimeout(function(){_this.on_timeout();}, this.current_update_interval()); + }; + + // to be called once on startup + start(fn) { + this.m_fn = fn; + var _this = this; + this.update_timer = setTimeout(function(){_this.on_timeout();}, this.current_update_interval()); + }; + + // to be called on activity: + // * changes from remote + // * changes by ourselves + // * local activity, e.g. mouse move, or key presses + reset() { + if (!this.fast_mode()) { + this.update_counter = 0; + clearTimeout(this.update_timer); + var _this = this; + this.update_timer = setTimeout(function(){_this.on_timeout();}, this.current_update_interval()); + } else { + this.update_counter = 0; + } + }; +} + +var timer = new AdjustingTimer(); + function init_board() { var xhr = new XMLHttpRequest(); @@ -35,7 +94,10 @@ function init_board() { // Initialization done. Now we can start modifying. board.addEventListener("input", function() {on_modify(); }); - setInterval(function() {checkupdate();}, 2000); + // Initialization done. Now we can start modifying. + document.addEventListener("mousemove", function() {timer.reset(); }); + + timer.start(checkupdate); } reader.readAsBinaryString(file); @@ -121,8 +183,11 @@ function redirect_to_new_page() //set_status("Please wait while server prepares " + filename + " ..."); } +// local change done function on_modify() { + timer.reset(); + var xhr = new XMLHttpRequest(); // run on data received back @@ -196,6 +261,7 @@ function checkupdate() { // no change if response is text/plain if (this.getResponseHeader("Content-Type") == "application/octet-stream") { + timer.reset(); var file = new Blob([this.response]); reader = new FileReader(); reader.onload = function() { -- cgit v1.2.3