1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
import { initTimeVisualizer } from './timeVisualizer.js';
let polling = true
const blocks = {
time: { interval: 30 * 1000, lastUpdate: 0, update: updateTime }, // 30s
weather: { interval: 30 * 60000, lastUpdate: 0, update: updateWeather } // 30min
// Add more: { interval: X, lastUpdate: 0, update: updateFunction }
};
let lastPoll = 0;
function updateTime() {
fetch("/time")
.then(res => res.json())
.then(data => {
document.getElementById("weatherSummary").innerText = data.time;
});
}
function updateWeather() {
const city = document.getElementById("city").value;
fetch(`/weather?city=${encodeURIComponent(city)}`)
.then(res => res.json())
.then(data => {
if (!data) {
document.getElementById("weather-summary").innerText = `Error, "${city}" city not found`;
return
}
document.getElementById("weather-summary").innerText = data.summary;
document.getElementById("weather-icon").src = data.icon_url;
});
}
function pollUpdates() {
if (!polling) return;
const now = Date.now();
Object.keys(blocks).forEach(key => {
const block = blocks[key];
if (now - block.lastUpdate >= block.interval) {
block.update();
block.lastUpdate = now;
}
});
lastPoll = now;
}
function reloadAll() {
Object.keys(blocks).forEach(key => {
blocks[key].update();
blocks[key].lastUpdate = Date.now();
});
}
// Header controls
document.getElementById("reload").addEventListener("click", reloadAll);
document.getElementById("pause").addEventListener("change", (e) => {
polling = e.target.checked;
});
// Initial load
reloadAll();
// Poll every 500ms to check intervals (fast enough for 1s updates, light on CPU)
// maybe the 1s updates should be special case, but for now let's keep it simple
setInterval(pollUpdates, 500);
// timeVisualizer
initTimeVisualizer('timeVisualizer');
|