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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, thanks for the feedback @cjbeattie! I forgot I made this gist. 😅