Skip to content

Instantly share code, notes, and snippets.

@meduzen
Last active November 24, 2023 12:56
Show Gist options
  • 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;
@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