42 lines
1.2 KiB
JavaScript

const EnumSessionWorker = Object.freeze({
MESSAGE: 'SessionWorker.MESSAGE',
START: 'SessionWorker.START',
CLEAR: 'SessionWorker.CLEAR',
TIMEOUT: 'SessionWorker.TIMEOUT',
});
let timeout = null;
let sessionTime = null;
function getCurrentTime(){
return Intl.DateTimeFormat('it-IT', {hour: '2-digit', minute: '2-digit', second: '2-digit'}).format(new Date());
}
function mt(m){
return `${getCurrentTime} - [sessionWorker]: ${m}`;
}
onmessage = function (ev) {
const sessionExpired = () => {
console.log(mt('session EXPIRED'));
postMessage({type: EnumSessionWorker.TIMEOUT})
}
const { type, data } = ev.data;
if (type === EnumSessionWorker.START){
console.log(mt('START session'));
const sessionExpiration = data;
sessionTime = sessionExpiration;
timeout = setTimeout(sessionExpired, sessionTime);
} else if (type === EnumSessionWorker.CLEAR){
console.log(mt('CLEAR session'));
clearTimeout(timeout);
timeout = setTimeout(sessionExpired, sessionTime);
} else { //EnumSessionWorker.MESSAGE
const message = data;
console.log(mt('message recieved'), message);
}
postMessage({ type, data: 'OK' });
}