forked from hiteshchoudhary/basic-server-check
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
146 lines (127 loc) · 5.12 KB
/
script.js
File metadata and controls
146 lines (127 loc) · 5.12 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
const grid = document.getElementById('checkbox-grid');
const totalConnectionsElement = document.getElementById('total-connections');
const activeUsersElement = document.getElementById('active-users');
const connectBtn = document.getElementById('connect-btn');
const usernameInput = document.getElementById('username-input');
const usernameDisplay = document.getElementById('username-display');
const timerElement = document.createElement('div'); // Timer display
let checkboxes = new Array(100000).fill(false);
let ws;
let countdownInterval;
const CHECKBOX_BATCH_SIZE = 500; // Number of checkboxes to load at a time
let loadedCheckboxes = 0; // Track how many checkboxes have been loaded
let isConnected = false; // Track connection status
// Automatically connect to WebSocket to get initial stats and checkbox state
connectToWebSocket();
function connectToWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
const host = window.location.host;
const wsUrl = `${protocol}://${host}/`;
ws = new WebSocket(wsUrl);
ws.onopen = () => {
console.log('WebSocket connection opened');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (Array.isArray(data)) {
// Received checkbox state array
checkboxes = data;
renderCheckboxes();
} else if (data.totalConnections !== undefined && data.activeUsers !== undefined) {
// Received stats update
totalConnectionsElement.textContent = data.totalConnections;
activeUsersElement.textContent = data.activeUsers;
} else if (data.index !== undefined && data.checked !== undefined) {
// Received individual checkbox update
checkboxes[data.index] = data.checked;
updateCheckbox(data.index, data.checked);
}
};
ws.onclose = () => {
console.log('WebSocket connection closed');
connectBtn.style.display = 'inline-block';
grid.style.display = 'none';
timerElement.textContent = ''; // Clear the timer display
isConnected = false; // Reset connection status
disableCheckboxes(); // Disable checkboxes on disconnect
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
function startConnection() {
grid.style.display = 'grid';
connectBtn.style.display = 'none';
usernameDisplay.appendChild(timerElement); // Add the timer to the username display
startTimer();
isConnected = true; // Set connection status to true
enableCheckboxes(); // Enable checkboxes after connection
}
function handleCheckboxChange(index) {
if (!isConnected) return; // Prevent interaction if not connected
const newCheckedState = !checkboxes[index];
checkboxes[index] = newCheckedState;
ws.send(JSON.stringify({ index, checked: newCheckedState }));
}
function renderCheckboxes() {
const fragment = document.createDocumentFragment();
for (let i = loadedCheckboxes; i < Math.min(checkboxes.length, loadedCheckboxes + CHECKBOX_BATCH_SIZE); i++) {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = `checkbox-${i}`;
checkbox.className = 'checkbox';
checkbox.checked = checkboxes[i];
checkbox.disabled = !isConnected; // Disable or enable based on connection status
checkbox.onchange = () => handleCheckboxChange(i);
fragment.appendChild(checkbox);
}
grid.appendChild(fragment);
loadedCheckboxes += CHECKBOX_BATCH_SIZE;
}
function updateCheckbox(index, checked) {
const checkbox = document.getElementById(`checkbox-${index}`);
if (checkbox) {
checkbox.checked = checked;
}
}
function startTimer() {
let timeLeft = 60;
timerElement.textContent = `Time remaining: ${timeLeft}s`;
countdownInterval = setInterval(() => {
timeLeft--;
timerElement.textContent = `Time remaining: ${timeLeft}s`;
if (timeLeft <= 0) {
clearInterval(countdownInterval);
ws.close();
disableCheckboxes(); // Disable all checkboxes when the timer ends
}
}, 1000);
}
function enableCheckboxes() {
document.querySelectorAll('.checkbox').forEach(checkbox => {
checkbox.disabled = false;
});
}
function disableCheckboxes() {
document.querySelectorAll('.checkbox').forEach(checkbox => {
checkbox.disabled = true;
});
grid.style.display = 'none'; // Hide the grid after disconnection
connectBtn.style.display = 'inline-block'; // Show the connect button again
}
// Lazy loading: load more checkboxes as the user scrolls
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
renderCheckboxes();
}
});
usernameInput.addEventListener('input', () => {
const username = usernameInput.value.trim();
connectBtn.disabled = username === '';
usernameDisplay.textContent = username ? `Welcome, ${username}` : '';
});
connectBtn.addEventListener('click', () => {
startConnection();
});
// Initial rendering of checkboxes
renderCheckboxes();