major697
major697

Reputation: 1862

Vuex can't stop setInteval

I have a method in Vuex:

export const startTime = ({ commit, state }, status) => {
    let timeInterval
    
    if(status) {
        const timer = 1000
        timeInterval = setInterval(() => {
            console.log('x')
            commit('SET_RUNNED_TIME', parseInt(state.runnedTime += timer))
        }, timer)
    }
    else {
        console.log('y')
        clearInterval(timeInterval)
        commit('SET_RUNNED_TIME', 0)
    }
}

From my component I send value true or false to method startTime(). When I send true then method run commit SET_RUNNED_TIME. But when I send false clearInterval(timeInterval) not stopping setInterval and still is sending commit('SET_RUNNED_TIME' ...)

Upvotes: 0

Views: 145

Answers (1)

glazjoon
glazjoon

Reputation: 654

The variable timeInterval is inside the scope of the function. If you want it to keep on living between different calls to startTime you need to put it outside the function scope. For example in the state.

Upvotes: 1

Related Questions