Uses timeout instead of interval

This commit is contained in:
Mouse Reeve 2021-01-19 14:59:46 -08:00
parent 94a41498cf
commit 1778e8dd46

View file

@ -34,23 +34,25 @@ window.onload = function() {
// polling // polling
document.querySelectorAll('[data-poll]') document.querySelectorAll('[data-poll]')
.forEach(t => setInterval(function () { polling(t); }, 10000)); .forEach(el => polling(el));
}; };
function polling(el) { function polling(el) {
// poll the endpoint let delay = 10000 + (Math.random() * 1000);
fetch('/api/updates/' + el.getAttribute('data-poll'), { setTimeout(function() {
method : "GET", fetch('/api/updates/' + el.getAttribute('data-poll'))
}).then(response => response.json()) .then(response => response.json())
.then(data => updateCountElement(el, data)); .then(data => updateCountElement(el, data));
polling(el);
}, delay, el);
} }
function updateCountElement(el, data) { function updateCountElement(el, data) {
const currentCount = el.innerHTML; const currentCount = el.innerText;
const count = data[el.getAttribute('data-poll')]; const count = data[el.getAttribute('data-poll')];
if (count != currentCount) { if (count != currentCount) {
addRemoveClass(el, 'hidden', count < 1); addRemoveClass(el, 'hidden', count < 1);
el.innerHTML = count; el.innerText = count;
} }
} }