Select Git revision
StructuralElement.php
Forked from
Stud.IP / Stud.IP
Source project has a limited visibility.
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
jsupdater.js 7.14 KiB
/* ------------------------------------------------------------------------
* JSUpdater - periodically polls for new data from server
* ------------------------------------------------------------------------
* Exposes the following method on the global STUDIP.JSUpdater object:
*
* - start()
* - stop()
* - register(index, callback, data)
* - unregister(index)
*
* Refer to the according function definitions for further info.
* ------------------------------------------------------------------------ */
import { $gettext } from './gettext.js';
import Dialog from './dialog.js';
let active = false;
let lastAjaxDuration = 200; //ms of the duration of an ajax-call
let currentDelayFactor = 0;
let lastJsonResult = null;
let dateOfLastCall = +new Date(); // Get milliseconds of date object
let serverTimestamp = STUDIP.server_timestamp;
let ajaxRequest = null;
let timeout = null;
let registeredHandlers = {};
// Reset json memory, used to delay polling if consecutive requests always
// return the same result
function resetJSONMemory(json) {
if (json.hasOwnProperty('server_timestamp')) {
delete json.server_timestamp;
}
json = JSON.stringify(json);
if (json !== lastJsonResult) {
currentDelayFactor = 0;
}
lastJsonResult = json;
}
// Process returned json object by calling registered handlers
function process(json) {
for (const [index, value] of Object.entries(json)) {
// Set timestamp
if (index === 'server_timestamp') {
serverTimestamp = value;
} else {
// Call registered handler callback by index
if (index in registeredHandlers) {
registeredHandlers[index].callback(value);
}
}
}
// Reset json memory
resetJSONMemory(json);
}
// Registers next poll
function registerNextPoll() {
// Calculate smallest registered polling interval (but no more than 60 seconds)
let interval = 60000;
for (const [index, handler] of Object.entries(registeredHandlers)) {
if (handler.interval < interval) {
interval = handler.interval;
}
}
// Define delay by last poll request (respond to load on server) and
// current delay factor (respond to user activity)
var delay = (interval || lastAjaxDuration * 15) * Math.pow(1.33, currentDelayFactor);