Skip to content

Instantly share code, notes, and snippets.

@OriginalEXE
Last active May 16, 2022 12:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OriginalEXE/e15b700eaad2605eb81803041191514c to your computer and use it in GitHub Desktop.
Save OriginalEXE/e15b700eaad2605eb81803041191514c to your computer and use it in GitHub Desktop.
An interface that handles timers based on the user activity
const ActivityBasedTimer = () => {
let globalTimerId = 0;
const timers = new Map();
const maybeExecuteTimerCallback = ({ timerId, forced = false }) => {
const timer = timers.get(timerId);
if (timer === undefined) {
return;
}
const {
callback,
interval,
forcedInterval,
forcedIntervalId,
lastExecution,
} = timer;
const intervalToCheckFor = forced === true
? forcedInterval
: interval;
const now = Date.now();
if (now - lastExecution < intervalToCheckFor) {
return;
}
const newTimer = {
...timer,
lastExecution: now,
};
if (forcedIntervalId !== undefined) {
window.clearInterval(forcedIntervalId);
newTimer.forcedIntervalId = window.setInterval(() => {
maybeExecuteTimerCallback({ timerId, forced: true });
}, forcedInterval);
}
timers.set(timerId, newTimer);
callback({ forced, timerId });
};
const setInterval = ({ callback, interval, forcedInterval } = {}) => {
const timerId = globalTimerId;
if (typeof callback !== 'function' || typeof interval !== 'number') {
return undefined;
}
const timer = {
callback,
interval,
lastExecution: Date.now(),
};
if (forcedInterval !== undefined) {
timer.forcedInterval = forcedInterval;
timer.forcedIntervalId = window.setInterval(() => {
maybeExecuteTimerCallback({ timerId, forced: true });
}, forcedInterval);
}
timers.set(timerId, timer);
globalTimerId += 1;
return timerId;
};
const clearInterval = (timerId) => {
const timer = timers.get(timerId);
if (timer === undefined) {
return;
}
const { forcedIntervalId } = timer;
if (forcedIntervalId !== undefined) {
window.clearInterval(forcedIntervalId);
}
timers.delete(timerId);
};
const runTimersCheck = () => {
timers.forEach((_timer, timerId) => {
maybeExecuteTimerCallback({ timerId });
});
};
return {
setInterval,
clearInterval,
runTimersCheck,
};
};
export default ActivityBasedTimer;
router.beforeEach((to, from, next) => {
versioningTimer.runTimersCheck();
next();
});
import ActivityBasedTimer from '@/services/activityBasedTimer';
const versioningTimer = new ActivityBasedTimer();
versioningTimer.setInterval({
async callback() {
const newVersionAvailable = await isNewerVersionAvailable();
if (!newVersionAvailable) {
return;
}
store.commit('setNewVersionAvailable', true);
},
// Normal interval is once every 10 minutes
interval: 1000 * 60 * 10,
// Forced interval is once per day
forcedInterval: 1000 * 60 * 60 * 24,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment