@toruslabs/broadcast-channel
Version:
A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers
50 lines (47 loc) • 1.39 kB
JavaScript
import { microSeconds as microSeconds$1 } from '../util.js';
const microSeconds = microSeconds$1;
const type = "simulate";
const SIMULATE_CHANNELS = new Set();
const SIMULATE_DELAY_TIME = 5;
function create(channelName) {
const state = {
time: microSeconds$1(),
name: channelName,
messagesCallback: null
};
SIMULATE_CHANNELS.add(state);
return state;
}
function close(channelState) {
SIMULATE_CHANNELS.delete(channelState);
}
function postMessage(channelState, messageJson) {
return new Promise(resolve => {
setTimeout(() => {
const channelArray = Array.from(SIMULATE_CHANNELS);
channelArray.forEach(channel => {
if (channel.name === channelState.name &&
// has same name
channel !== channelState &&
// not own channel
!!channel.messagesCallback &&
// has subscribers
channel.time < messageJson.time // channel not created after postMessage() call
) {
channel.messagesCallback(messageJson);
}
});
resolve();
}, SIMULATE_DELAY_TIME);
});
}
function onMessage(channelState, fn) {
channelState.messagesCallback = fn;
}
function canBeUsed() {
return true;
}
function averageResponseTime() {
return SIMULATE_DELAY_TIME;
}
export { SIMULATE_DELAY_TIME, averageResponseTime, canBeUsed, close, create, microSeconds, onMessage, postMessage, type };