dylanolv
dylanolv

Reputation: 57

How to ClearInterval in Vuex

I'm trying to clear an interval in my vuex store but it doesn't work.

In startCounter I check if my count is equal to 100 to clear the interval in stopCounter with

clearInterval(this.myCounterInterval);

Here is my code, thank you.

import Vue from "vue";
import Vuex from "vuex";
import videos from "@/models/videos";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0,
    totalTime: 20,
    myCounterInterval: 0,
    visible: false,
    show: false,
    videos: {
      type: Array,
      default: () => videos
    }
  },
  mutations: {
    visibleProgressBar (state) {
      state.visible = true;
    },
    invisibleProgressBar (state) {
      state.visible = false;
    },
    showModal (state) {
      state.show = true;
    },
    hideModal (state) {
      state.show = false;
    },
    countDown (state) {
      if(state.totalTime >= 1) {
        state.totalTime--;
        state.count += 5;
      } else {
        state.totalTime = 0;
        state.count = 0;
        return;
      }
    },
    setCounter (state, newCount) {
      state.count = newCount;
    },
    stopCounter (state) {
      clearInterval(this.myCounterInterval);
      state.count = 0;
    },
    setVideos (state) {
      state.videos;
    }
  },
  actions: {
    startCounter ({ state, commit }) {

      this.myCounterInterval = commit("setCounter", setInterval(() => {
        commit("countDown");

        if(state.count === 100) {
          commit("stopCounter");
        }
      }, 1000));
    },
    stopCounter ({ commit }) {
      commit("stopCounter");
    },
    showProgressBar ({ commit }) {
      commit("visibleProgressBar");
    },
    hideProgressBar ({ commit }) {
      commit("invisibleProgressBar");
    },
    showModal ({ commit }) {
      commit("showModal");
    },
    hideModal ({ commit }) {
      commit("hideModal");
    },
    getVideos ({ commit }) {
      commit("setVideos");
    }
  },
  modules: {}
});

Upvotes: 3

Views: 2314

Answers (2)

frozen_fly
frozen_fly

Reputation: 1

You need to remove this assignment:

this.myCounterInterval = commit("setCounter", setInterval(() => {

, and just commit:

commit("setCounter", setInterval(() => {

"setCounter" mutation assigns your counter to a state.count:

setCounter (state, newCount) {
  state.count = newCount;
}

, and then you can delete this interval:

stopCounter (state) {
  clearInterval(state.count);
}

This one works for me

Upvotes: 0

Vagan M.
Vagan M.

Reputation: 463

You can do something like this

stopCounter (state) {
    state.myCounterInterval = null
    ...
},

Set interval like this

actions

startCounter ({ state, commit }) {
      commit("setCounter")
}

mutations

setCounter (state) {
   state.count = 0;
   state.myCounterInterval = setInterval(() => {
      your logic
   }, 1000))
},

Upvotes: 4

Related Questions