What is the best way to stop a Vue.js state using clearInterval()?

In my Vuex code, I currently have the following:


export default new Vuex.Store({
    state: { 
        intervalVar: 0
    },

    mutations: {
        SET(state, {key, value}) {
            state[key] = value
        },
    },

    actions: {
        doSomething({commit}) {
            commit("SET", {
                key: 'intervalVar',
                value: setInterval( () => console.log('hi'), 30000)
            })
        }, 
    }, 
})

While I assign the value of setInterval to state.intervalVar, I am unsure of how to properly clear this interval using state.intervalVar.

Answer №1

To perform a SET mutation, you can pass the value 0:

actions: {
    stopTime({state, commit}) {
        clearInterval(state.intervalVar)
        commit("SET", {
            key: 'intervalVar',
            value: 0,
        })
    }, 
}, 

Answer №2

Is there a way to easily stop the interval by adding a new action?

export default new Vuex.Store({
    state: { 
        intervalVar: 0
    },
    mutations: {
        SET(state, {key, value}) {
            state[key] = value
        },
        CLEAR(state, key) {
            clearInterval(state[key]);
        }
    },

    actions: {
        async doSomething({commit}) {
            commit("SET", {
                key: 'intervalVar',
                value: setInterval( () => console.log('hi'), 30000)
            })
        },
        clearSomething({ commit }) {
            commit('CLEAR', 'intervalVar');
        }
    }, 
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery .load function does not function properly when an ajax query is already underway

My web application utilizes dynamic loading of content within the same div (.content) through either an ajax request or a .load() request. An example of the ajax request code snippet is: $(document).on('click', '.button1', functio ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Unable to access the POST value in the current context

I am having trouble retrieving the values from a simple form that consists of two files: APP.js and FORM.ejs. I am attempting to get the values submitted through the form. APP.js: const http = require('http'); const express = require("express"); ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Easily move a group of HTML elements at the same time with a simple

Exploring HTML5 Drag and Drop with Multiple Elements When it comes to dragging and dropping multiple elements in HTML5, there seems to be a limitation with the default draggable attribute. This attribute allows only one element to be dragged at a time, ma ...

What is the best way to implement a custom toast delay in a React application using setTimeout

The concept is straightforward: When the function showToast is called, I aim to change my toast's className to show, and then remove it by replacing with an empty string after displaying it for 3 seconds. HTML: <div id="toast">New col ...

Creating identical HTML output using PHP and JavaScript

Often when working with PHP, I find myself creating helper functions that generate complex HTML. For example, ensuring the accessibility and error-handling capabilities of form elements can be a challenging task, so I will have a PHP function to handle thi ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Adjusting div position because of navigation bar elements above

I have implemented Bootstrap to create navigation tabs on my website. Currently, I have two navigation bars within a single div element. While they are functioning correctly, I am facing an issue where toggling through the tabs changes the height of the co ...

Choose the div without a class

I currently have several divs displayed on my website. <div class="slide bx-clone"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide bx-clone"></div> <div class="slide bx-clone" ...

Vue 2.0 custom filter not producing any output

I am attempting to create a customized filter that identifies and returns the items that correspond to a given input. It functions effectively with basic arrays like ['Apple', 'Banana', 'Cupple'], but encounters difficulty whe ...

What is the best way to determine the value of a variable specific to my scenario?

Using the Angular framework, I am trying to determine if the data variable updates when a button is clicked. Here is an example: <button ng-click='change()'>{{data}}</button> I want to verify if the data changes or log the data var ...

How can I select the div inside the second to last li element?

Within a particular list item, I have three divs. I am trying to target the second to last list item which contains a div with the class 'designnone'. Here's what I have so far: $('div[groupname=' + groupName + ']').find ...

Connecting socket.io to a Vue.js single page application using Javascript

I am new to Vue.js, Socket.io, and Node.js. Recently, I developed a single-page application that allows communication between a Node.js server running on a Raspberry Pi and a Siemens S7-1500 PLC connected via Ethernet. The Raspberry Pi acts as a WiFi acces ...

Generate a list item that is contenteditable and includes a button for deletion placed beside it

I am attempting to create a ul, where each li is set as contenteditable and has a delete button positioned to the left of that li. My initial attempt looked like this: <ul id='list'> <li type='disc' id='li1' cl ...

What is the best way to create a fade effect when toggling the class "hover"?

I've searched and searched online, but haven't found a solution. I want a specific section of my webpage to gradually appear when I hover over it. Below is the CSS code I'm using: .status .admin { display: none; } .status.hover .adm ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...

Mastering universal code creation with the composition API in Quasar

The Quasar website explains that for writing universal code, the created and beforeCreate lifecycle hooks in Vue components are executed in Server Side Rendering (SSR). This raises a question: What about setup? How can I achieve SSR functionality with th ...

Differences between using Array.from and a for loop to iterate through an array-like object

When traversing an array-like object, which method is more efficient for performance: using Array.from( ).forEach() or a traditional for loop? An example of an array-like object would be: let elements = document.querySelector('#someid').children ...

I am unable to find the URL /receipt on this server, however it is functioning properly on localhost

Everything is functioning perfectly on my localhost, but once I publish the website and try to access it, I encounter an error that says "Failed to load resource: the server responded with a status of 404 (Not Found)". Let's take a look at the code s ...