Suspend features for moving between pages in history

In the application, we have two main pages - Home.vue and Statistics.vue. The Home.vue page renders the TableFields.vue component. On the Home page, there are fields with numbers that have an initial value of "3" set upon page load. An interval running a calculate function adds numbers every two seconds. How can we ensure that when transitioning from '/' to '/statistics', all ongoing calculations are paused, and then resumed when returning back? Below each field on the home page, there are buttons that toggle the setInterval() function to stop or resume the calculations. Essentially, when moving from "/" to "/statistics", we need to trigger clearInterval() to stop the calculations on the "/" page. @Saksham TableFields.vue:

<template>
  <div>
    <table class="table-a">
      <tr>
        <th>A</th>
        <td class="sign">{{ this.randomSign.A }}</td>
        <td>{{ initialValue.A }}</td>
        <td v-show="this.randomSign.A == '+'">&#x2B06;</td>
        <td v-show="this.randomSign.A == '-'">&#x2B07;</td>
      </tr>
    </table>
    <button @click="toggleIntervalA()">
      <span v-show="this.startStop.A">Stop</span>
      <span v-show="!this.startStop.A">Start</span>
    </button>
    <table class="table-b">
      <tr>
        <th>B</th>
        <td class="sign">{{ this.randomSign.B }}</td>
        <td>{{ initialValue.B }}</td>
        <td v-show="this.randomSign.B == '+'">&#x2B06;</td>
        <td v-show="this.randomSign.B == '-'">&#x2B07;</td>
      </tr>
    </table>
    <button @click="toggleIntervalB()">
      <span v-show="this.startStop.B">Stop</span>
      <span v-show="!this.startStop.B">Start</span>
    </button>
  </div>
</template>

<script>

export default {
  name: 'TableFields',
  props: {
    changesA: {
      type: Array,
      required: false
    },
    changesB: {
      type: Array,
      required: false
    }
  },
  data () {
    return {
      // Data properties removed for brevity
    }
  },
  methods: {
    // Methods logic removed for brevity
  },
  mounted () {
    // Mounted logic removed for brevity
  },
  beforeDestroy () {
    // Before destroy logic removed for brevity
  }
}
</script>

<style lang="scss" scoped>
// Styling rules removed for brevity
</style>

Project repository: link

Answer №1

Consider implementing the beforeDestroy() hook to transfer the counter to either the root component or the Vuex store (if applicable). Then, retrieve the counter in the mounted() hook when returning to the route to continue from where you left off.

Here's an example of how to use this in your component:

export default {
...
    beforeDestroy () {
        this.$root.counter = this.counter;
    },
    mounted () {
        this.counter = this.$root.counter || 0;
    }
...
}

I have set up a demo in a sandbox at https://codesandbox.io/s/preserve-timer-state-2osi7, which maintains the timer state even when navigating away and resumes it accordingly.

Additional Note:

Based on your comment, it appears that you are trying to assign a value to a property within an undefined object. Initially, there is no initialValue property in the root component, and you are attempting to access a nested property A.

You should first verify if initialValue exists before accessing A:

this.initialValue.A = this.$root.initialValue && this.$root.initialValue.A ?  this.$root.initialValue.A : 3

Also, ensure that your data includes initialValue as an empty object:

initialValue: {}

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

Enhancing image clips using jQuery techniques

Could someone help me figure out why the image clip value isn't changing when I move the range slider in the code below? $('#myRange').on('input', function() { var nn = $(this).val(); $("img").css({ 'clip': ...

Combine various canvases into a single one (for exporting purposes) with pure Javascript

I'm currently faced with a unique challenge involving the creation of around 200 canvases, each showcasing an image captured from the user's webcam as part of an experimentation process for the "photo finish" technique. My task now is to export ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

Trying to assign a property to an undefined variable inside a function

At the moment, I am configuring error messages on a login page for an extension using vue, and encountering issues within the importCreds() function. data(){ return { url:'', apikey:'', error:'', } }, meth ...

Is adding ng-click in a template counterproductive to the concept of MV* architecture?

When working with AngularJS, you may come across instances where the ng-click handler is directly connected to an HTML element like <a> or <button>. Take for example the snippet below (borrowed from an Angular homepage sample), where the click ...

Unexpected issue: Ajax success function not displaying anything in the console

My code seems to be running without any output in the console. I am attempting to verify the data in order to trigger specific actions based on whether it is correct or not. However, the if-else conditions are not functioning as expected. Below is a snip ...

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

Executing all middleware within an express route

Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below: Router.route('/:id/documents') .get([isAuthenticated, ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Utilizing JavaScript to access and present results from a PHP file located on a separate server

UPDATE I have set the header of my php file as shown below: header("Access-Control-Allow-Origin: *"); Currently, this is the error I am seeing in my browser: "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Heade ...

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

Tips for incorporating a multiple tag search feature within my image collection using JavaScript?

I am facing a challenge with my image gallery search feature. Currently, users can search for images by typing in the title or tag of an image. However, I need to enhance this functionality to allow for multiple tags to be searched at once. For example, if ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

Discovering a website's console content using the "web-request" npm package

I recently added the web-request NPM package to my project with the goal of retrieving console messages from a specific website. However, I encountered an issue as I was unsure of how to achieve this. var result = await WebRequest.get('http://disco ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

An 'Syntax Error' message appears in Internet Explorer when JSONP does not receive a response

Our current application needs to retrieve information from another application, and this second application does not have to be active to respond to the JSONP request. In this case, the requester will receive an alert message informing them of this. funct ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...