Deactivate a setInterval function within a Vue.js component

I am facing an issue in my VUE SPA where I have a component running a recursive countdown using setInterval functions. The problem is that the countdown continues running in the background even when I switch to another view, but I want to destroy the setInterval once I switch views.

I attempted to use a global data variable to store the countdowns and then destroy it in the destroyed hook, but unfortunately, it did not work as expected.

Below is a snippet of my code:

    data: function () {
        return {
            counters: ""
        }
    }),

   methods: {
     countdown(index, exp) {
        ...
          this.counters = setInterva()
        ...
        },
   },

   destroyed(){
        console.log(this.counters); // returns a progressive integer
        clearInterval(this.counters);
        console.log(this.counters); // returns same integer
        this.counters = 0;
        console.log("destroyed");
    } 

However, when checking in the console, I observed the following:

destroyed

app.js:64433 0

app.js:64398 Missing counter_1 . <--- which indicates that the counter is still running

If anyone has any suggestions or solutions, it would be greatly appreciated!

Answer №1

There are two potential scenarios to consider based on whether or not the function countdown is being called:

1. The function countdown is not being called

In this case, ensure that countdown(index, exp) is defined within the created hook as shown below. Additionally, bind a method foo() to an interval for the desired functionality.

  created: function(){
      this.counterInterval =  setInterval(
        function()
        {
          this.foo();
        }.bind(this), 500);
    return this.foo();
  },
  destroyed: function(){
    clearInterval( this.counterInterval )
  },

2. The function countdown is being called correctly but the component is not being destroyed

If the issue lies in misunderstanding how to "destroy" the component resulting in it not being destroyed, you can use the same code as above. Simply add a data property of isShowing: true within the JSX to resolve the issue.

Perform a v-if check on isShowing and set up an event listener to determine if the element is in view. If the element is in view, then isShowing===true, otherwise false.

Answer №2

The destroy() and beforeDestroy() methods have been marked as obsolete in vue3.

It is recommended to use unmount() or beforeUnmount() instead.

beforeUnmount(){
    clearTimeout(this.timer);
}

Answer №4

Give this a shot: Switch out the destroyed() method for beforeDestroy().

Update:

It's possible that the Vue component was not properly destroyed. Try manually destroying it.

Apologies for any language mistakes. Thank you!

Answer №5

Implement the beforeRouteLeave route navigation guard within your route components to properly handle destroying setInterval functions. By adding a clearInterval function inside the beforeRouteLeave method, you can ensure that any timers set by setInterval are properly destroyed before exiting the component.

beforeRouteLeave (to, from, next) {
    clearInterval(this.timers);
    next()
},

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

Tips for avoiding Netlify's error treatment of warnings due to process.env.CI being set to true

Recently, I encountered an issue with deploying new projects on Netlify. After reviewing the logs, I noticed a message that had never appeared during previous successful deployments: The build failed while treating warnings as errors due to process.env.CI ...

What is the best way to incorporate bullet points into a textarea?

How can I make a bullet point appear when pressing the 'enter' button inside a textarea? I tried using this code, but it doesn't seem to work. Any suggestions? <script> $(".todolist").focus(function() { if(document.getElementById( ...

How to properly adjust HTTP headers within an AngularJS factory

Looking for guidance from an Angular expert. I want to know how to modify the header for POST in the code snippet below: 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'? The provided code is as follows: var tableMod ...

Ways to implement a setTimeout function to return to the initial div element?

I have a unique setup on my webpage with three divs. The first div features an html5 video, the second div contains buttons for interaction, and the third div acts as a thank you page that loops back to the beginning like a photo slide. I have shared my co ...

Is JsonEditor capable of editing JSON Schemas effectively?

For a while now, I have been impressed by the functionality of JSON-editor and have been using it to edit documents based on a specific JSON schema. But why stop there? Many users utilize JSON-Editor to make changes to JSON documents according to the corr ...

How can I ensure that each callback is passed a distinct UUID?

I am utilizing a package called multer-s3-transform to modify the incoming image before uploading it to my bucket. Below is the code snippet of how I am implementing this: const singleImageUploadJpg = multer({ storage: multerS3({ s3: s3, bucket: ...

Guide on setting up Sentry Vite-Plugin to upload sourcemaps within Quasar

Currently, I'm in the process of setting up error reporting for my Vue.js SPA application following Sentry's documentation. To enable Sentry to capture errors, a sourcemap is required due to minification during the build process, which Vite gener ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

Utilizing string interpolation within the parameters of an AJAX call

I have a locale variable that can hold values such as en, fr, or es. The goal is to include this locale key in an AJAX request as part of the data parameter. let locale = "en"; let name = "example"; $.ajax({ url: "/path", method: "PUT", data: {chara ...

Steps to open and configure a Mobile-Angular modal from another controller

Is it possible to use a modal in Angular JS for mobile devices without compromising the layout? I'm having trouble setting up the controller for my modal inside my main controller and passing parameters. Should I consider using ui-bootstrap for this p ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

What Causes the Undefined Value of "this" in Vue 3 Functions?

Here is a basic example of a component in Vue 3: <script> import { defineComponent } from 'vue' export default defineComponent({ name: 'Test', setup(){ return{ one, two } } }) function one(){ console. ...

Using jQuery to send data with an AJAX post request when submitting a form with

This is the code I'm working with: <html> <body> <?php include('header.php'); ?> <div class="page_rank"> <form name="search" id="searchForm" method="post"> <span class="my_up_text">ENTER THE WEBSITE TO ...

Troubleshoot the issue of ng-click not functioning properly when used in conjunction with ng-repeat with direct expressions

Having some trouble with an ng-repeat block and setting a $scope variable to true with an ng-click expression. It doesn't seem to be working as expected. Can anyone help out? Check the plnkr for more information. HTML: selected: {{selected}} < ...

The D3.js text element is failing to show the output of a function

I'm having an issue with my chart where the function is being displayed instead of the actual value. How can I make sure the return value of the function is displayed instead? The temperature values are showing up correctly. Additionally, the \n ...

Adjusting widths of strokes in React Native Vector Icons

I selected an icon from the react-native-vector-icon library. For instance, let's use featherIcons. How can I include a stroke-width property to the react-native-vector-icons package? import FeatherIcon from 'react-native-vector-icons/Feather&ap ...

How can I implement callback functions in joi validation?

Exploring the World of Coding I came across a code snippet online that caught my attention, but upon closer inspection, I realized it used Hapi/Joi which is now considered outdated. My question is how can I modify this code to work with Joi? app.post(&apo ...

Can you explain the distinction between using angular.copy() and simply using an assignment (=) to assign values

When a button is clicked, I want to assign certain values using the event parameter. Here is the code: $scope.update = function(context) { $scope.master = context; }; The $scope.master has been assigned the values of user. Recently, I came across th ...

Nashorn poses a security threat due to its ClassFilter vulnerability

Encountering some troubles with Nashorn and came across a concerning security vulnerability highlighted here: It appears that someone can easily execute code using this command: this.engine.factory.scriptEngine.eval('java.lang.Runtime.getRuntime().ex ...

Retrieve a subsection of an object array based on a specified condition

How can I extract names from this dataset where the status is marked as completed? I have retrieved this information from an API and I need to store the names in a state specifically for those with a completed status. "data": [ { "st ...