-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLagNetwork.js
More file actions
29 lines (26 loc) · 872 Bytes
/
LagNetwork.js
File metadata and controls
29 lines (26 loc) · 872 Bytes
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
// =============================================================================
// A message queue with simulated network lag.
// =============================================================================
class LagNetwork {
constructor() {
this.messages = [];
}
// "Send" a message. Store each message with the timestamp when it should be
// received, to simulate lag.
send(lag_ms, message) {
this.messages.push({ recv_ts: +new Date() + lag_ms, payload: message });
}
// Returns a "received" message, or undefined if there are no messages available
// yet.
receive() {
var now = +new Date();
for (var i = 0; i < this.messages.length; i++) {
var message = this.messages[i];
if (message.recv_ts <= now) {
this.messages.splice(i, 1);
return message.payload;
}
}
}
}
export default LagNetwork;