-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinternetCheck.js
More file actions
69 lines (57 loc) · 2.38 KB
/
internetCheck.js
File metadata and controls
69 lines (57 loc) · 2.38 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
// internetCheck.js
class InternetCheck {
constructor({ slowThreshold = 1500, checkInterval = 5000 } = {}) {
this.slowThreshold = slowThreshold; // Time in ms above which the connection is considered slow
this.checkInterval = checkInterval; // Interval to check connection
this.isOnline = navigator.onLine; // Check if the browser detects online status
this.init();
}
init() {
// Listen for online and offline events from the browser
window.addEventListener('online', () => this.handleOnlineStatus(true));
window.addEventListener('offline', () => this.handleOnlineStatus(false));
// Start periodic checks for internet speed
this.checkConnectionSpeed();
// Continue checking at regular intervals
setInterval(() => this.checkConnectionSpeed(), this.checkInterval);
}
handleOnlineStatus(status) {
this.isOnline = status;
if (!status) {
console.log("The internet is down.");
this.notify("Internet is down.");
}
}
async checkConnectionSpeed() {
if (!this.isOnline) return;
const startTime = performance.now();
try {
// Attempt to fetch a small resource to measure speed
await fetch('', { mode: 'no-cors' });
const endTime = performance.now();
const duration = endTime - startTime;
if (duration > this.slowThreshold) {
console.log("The internet is slow.");
this.notify("Internet is slow.");
} else {
console.log("The internet connection is good.");
}
} catch (error) {
// Fetch failed, so the internet might be down
console.log("Failed to connect, possible internet issue.");
this.notify("Failed to check connection, internet might be down.");
}
}
notify(message) {
// Notify other parts of the app or developers that the internet is slow or down
const event = new CustomEvent('internetStatus', { detail: message });
window.dispatchEvent(event);
// Optionally, display a message to the user:
alert(message);
}
}
// To integrate this module:
const internetChecker = new InternetCheck({
slowThreshold: 1500, // Customize slow threshold (ms)
checkInterval: 5000 // Customize the check interval (ms)
});