Last active
November 24, 2023 12:56
-
-
Save meduzen/6ee1cd0d8a3ce589862801e9ddfb4ce9 to your computer and use it in GitHub Desktop.
Approach for using setInterval / setTimeout in a vue-x store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Hi @meduzen, this is really awesome! I was having a bit of trouble implementing something like this myself and your solution helped me out! 😄
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
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
andclearInterval
calls in mutations because they are mutatingstate.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.