Skip to content

Instantly share code, notes, and snippets.

@meduzen
Last active November 24, 2023 12:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meduzen/6ee1cd0d8a3ce589862801e9ddfb4ce9 to your computer and use it in GitHub Desktop.
Save meduzen/6ee1cd0d8a3ce589862801e9ddfb4ce9 to your computer and use it in GitHub Desktop.
Approach for using setInterval / setTimeout in a vue-x store
const MILLISECONDS_PER_MINUTES = 1000 * 60;
const state = {
now: (new Date()),
intervalTimer: null,
};
const mutations = {
now(state) {
state.now = new Date();
},
setIntervalTimer(state, callback) {
state.intervalTimer = setInterval(() => {
if (callback) {
callback();
}
}, MILLISECONDS_PER_MINUTES * 3);
},
clearIntervalTimer(state) {
if (state.intervalTimer) {
clearInterval(state.intervalTimer);
}
}
};
const actions = {
pollNow({ commit, state }) {
if (!state.intervalTimer) {
commit("setIntervalTimer", () => commit("now"));
}
},
clearPollNow({ commit }) {
commit("clearIntervalTimer");
},
};
const time = {
namespaced: true,
state,
mutations,
actions,
};
export default time;
@meduzen
Copy link
Author

meduzen commented Mar 9, 2021

What this store module does

It provides action that can start/stop a polling (setInterval) updating the current time (state.now) every 3 minutes.

Approach

I put both the setInterval and clearInterval calls in mutations because they are mutating state.intervalTimer.

setInterval is having a callback mutating another part (state.now), but the decision to mutate another property is driven in an action (pollNow).

I would love feedback on this approach.

@cjbeattie
Copy link

Hi @meduzen, this is really awesome! I was having a bit of trouble implementing something like this myself and your solution helped me out! 😄

@meduzen
Copy link
Author

meduzen commented Jun 13, 2022

Hey, thanks for the feedback @cjbeattie! I forgot I made this gist. 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment