Navigating the waters of managing setInterval within a Nuxt environment

Within my component, I have a timer that is initiated using setInterval in the mounted() hook.

Let's say this component is located at http://localhost:3000/some-route.
What is the best approach to call clearInterval() when navigating to another route such as http://localhost:3000/ in order to stop the timer?
I have attempted to use unmounted(), but the component does not always unmount when changing routes. If I return to the same route (/some-route), the setInterval function restarts since the component remounts.

How can I ensure that the interval is cleared every time a different route is accessed?

Answer №1

Once I tackled the task, it proved to be quite tricky due to its scope and interaction with this (primarily arrow functions). To ensure global availability, I paired it with Vuex but incorporating it within a component's upper scope for the variable is also plausible.

Below is a snippet of the code I implemented:

actionSetPolling({ state, dispatch }) {
  try {
    const myPolling = setInterval(async function () {
      if (someVariable !== 'COMPLETED') {
        // do stuff
      } else if (conditionToStop) {
        window.clearInterval(myPolling);
      }
    }, 2000);
    dispatch('setPollingId', myPolling);
  } catch (error) {
    console.warn('error during polling', error.response);
    window.clearInterval(state.pollingId); 
  }
}

The `setPollingId` action sets a `pollingId` mutation, allowing me to globally track it persistently.

When unmounting your component, you can utilize the same approach:

beforeDestroy() {
  window.clearInterval(state.pollingId);
},

While not necessarily the optimal method, using `setInterval` inherently feels cumbersome and inelegant, especially in a Single Page Application environment.

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

Creating PDFs from DOCX files using NodeJS and TypeScript

I'm struggling to convert a DOCX file to a PDF in NodeJS using NestJS and TypeScript. I've tried several methods, but they all seem to fail: @nativedocuments/docx-wasm: NativeDocuments is not functioning as expected. word2pdf: This project is ar ...

`Multiple Autocomplete feature that allows rendering of previously selected items`

I've encountered a slight issue with my autocomplete feature. On the same page, I have two different autocompletes set up. Both of them pull elements via ajax from separate sources and use the _render option to display the items. The problem arises wi ...

Strategies for breaking apart a large, monolithic Node.js JavaScript application

My node.js server application is expanding, and I am looking to split it into multiple files. Below is a snippet of the current monolithic server.js file: var express = require('express'); var app = express(); // other initialization code etc / ...

Accelerate the window.onload process

As a newcomer to javascript and Jquery, I am working with javascript code that generates a table of content based on <h2> and <h3> tags. However, I have noticed that it is running slow as it waits for the entire page to render. I attempted to ...

Can you tell me how to display the currently utilized Node.js version and path within npm?

I’m encountering a similar issue to the one discussed in this Stackoverflow thread: SyntaxError: Use of const in strict mode?. However, my problem arises when attempting to install Flux. I followed the steps outlined in the linked Stackoverflow question ...

Ensure that the entire webpage is optimized to display within the viewport

My goal is to make the entire website fit perfectly into the viewport without requiring any scrolling. The main pages I am focusing on are index, music, and contact, as the other two pages lead to external sources (you can find the link at the bottom of th ...

Sending Data in Angular JS

Looking for guidance on Angular JS as a newcomer. I have set up a form on my index.html page, and when the user fills in the details and hits submit, I want it to redirect to a details.html page where all the filled-in information can be displayed. HTML ...

Error message: UnhandledPromiseRejectionWarning in (Node.js, Express.js, MongoDB) - TypeError occurs when trying to access an undefined 'username' property

I'm struggling to fetch and print the post's author from mongodb using client-side code. Unfortunately, my current code is throwing an error. It is a fullstack javascript code and despite my efforts in searching for a solution, I couldn't fi ...

An error occurred due to an unexpected identifier, '_classCallCheck', while the import call was expecting exactly one

Encountering an unexpected identifier '_classCallCheck'. Import call requires precisely one argument. Having trouble with React Native. I have attempted every solution found on the internet, but none proved successful. Is there any way to upgrade ...

What is the best way to store the input value within a variable?

I am developing a new component that includes an input field and a button. The user is required to enter their nickname in the input field. This nickname, captured as the input value, needs to be stored in a variable. This variable is integral to a functio ...

Having trouble with my custom AngularJs service created using the factory method

Discovering a challenge with my current setup. I have implemented two separate controllers that handle adding 'country name' and 'price' to a list. Everything functions as expected when each button is clicked individually. However, when ...

HTTP request in Angular with specific body content and custom headers

My goal is to access the sample API request from , as demonstrated in the documentation: curl -H "api-key: 123ABC" \ -H "Content-Type: application/json" \ -X POST \ ...

Is there a way in Javascript or JQuery to determine if a function is currently executing, or is there a way to tap into a return event?

Let me paint a picture of a common scenario: there's a form with numerous inputs (around 60-70). Each input must undergo validation, and if it is invalid, the form returns false. To prevent multiple AJAX requests with visual feedback, I need to safegu ...

An issue has been encountered in NodeJS with a route that begins with a percent sign causing an error

I have a NodeJS server set up with the following backend configuration: app.use(express.static(__dirname)) app.get('/', function(req, res){ res.send('main page here') }); app.get('/*', function(req, res){ res.send(&apos ...

What is preventing the fetch from functioning properly within the nuxtServerInit of the store?

With my current project setup using Nuxt, I encountered an issue within the store's action code snippet: async nuxtServerInit({ commit }) { this.dispatch('fetchAllClients') }, async fetchAllClients({ commit, state }) { console.log(' ...

React Native: Changing Props Triggers Touch Event Cancellation

I am currently utilizing the react-native-gesture-handler library to construct a drag-and-drop sortable array of components. As I progress in the development, I am now focusing on incorporating animations into the functionality. To achieve this, I utilize ...

unable to see the follow button in the website's Vue component

I am struggling to locate the button on my website Let's take a look at the FollowButton.Vue code below: <template> <div> <button class="btn btn-primary ml-4">Follow Me Now</button> </div> </temp ...

execute bower install for the specified bower.json file

Let's say my current working directory is c:\foo\ while the script is running. I want to execute bower from there for the c:\foo\bar\bower.json file. This can be done in npm by using npm install --prefix c:\foo\bar. ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

Tips for resolving rendering page issues in an express app

My application is a straightforward blog platform that showcases a schema for the title, entry, and date of each blog post. There is also an edit/delete feature that is currently under development. When attempting to use the edit/delete button on a selecte ...