Pause the ongoing execution in JavaScript by using clearInterval

In my Vue 2.0 app, I have a line of code that calls this.refreshState() every minute using the following interval:

this.scheduler = setInterval(() => this.refreshState(), 60 * 1000)

Later in the code, I need to ensure that the execution loop is halted and that any instance of this.refreshState() currently running from the scheduler is also stopped (even if it's mid-operation).

Currently, I am using :

clearInterval(this.scheduler)

I am unsure whether clearInterval blocks the current execution. Unfortunately, I couldn't find an answer in the documentation.

For reference, here is the code for refreshState:

refreshState: function () {
   // API call to backend
    axios.get("/api/refreshState")
       .then(response => {
            this.states = response.data.states
        })
        .catch((err) => console.log(err))
}

Here's a scenario where I am concerned:

alterState: function (incremental_state) {
    clearInterval(this.scheduler) // ???
    axios.post("/api/alterState", incremental_state)
      .then(() => {
           this.refreshState()
           this.scheduler = setInterval(() => this.refreshState(), 60 * 1000)
        })
      .catch((err) => { console.log(error) })
}

I want to ensure that upon exiting alterState, the variable this.states incorporates the incremental state added.

Answer №1

Looking to ensure that upon exiting alterState, the state of this.states accurately reflects the addition of incremental state.

Your goal is to update the backend and have those changes reflected on the frontend. Yet currently, despite calling this.refreshState() immediately after a successful response from /api/alterState, the desired outcome is not achieved.

To address this issue, simply calling this.refreshState() may not suffice due to browser caching mechanisms. To circumvent this, consider either:

  • Configuring the endpoint to prevent caching by setting appropriate response headers.
  • Adding a unique parameter when calling the endpoint to force the browser to fetch fresh data every time.
  axios
    .get(`/api/refreshState?v=${Date.now()}`)
    .then...

The second approach is recommended for its reliability and independence from server settings.


In the scenario where no external sources modify the data apart from user interactions within the app, removing the use of setInterval is advised. However, if other entities do affect server-side data and continuous updates are necessary, your current implementation alongside refreshState() suffices without the need for interval cancellation.


Please provide clarification if my interpretation deviates from your actual query.
As a personal suggestion, renaming refreshState() to getState() is recommended as well.

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

Access the plugin object from a Vue.js 2 component using typescript

I devised a plugin object to handle the regular expressions used in my application in a more global manner. Here's an example of how it looks: import Vue from "vue"; Vue.prototype.$regex = { //isEmail function implementation goes here } ...

Initiate the command with given parameters

Currently, I am utilizing a combination of React, Redux, Rxjs, typesafe-actions, and TypeScript to invoke an action with parameters. Here is my current code: Actions: import { createAsyncAction } from 'typesafe-actions'; import {ICats} from &ap ...

Merging audio files using Node Stream

Currently facing an issue with joining 2 .wav files together, as my output file only contains the first item in the array: const writeStream = fs.createWriteStream('server/playback.wav'); const inputFiles = [ `${path.resolve(__dirname, 'r ...

Leveraging jQuery for invoking PHP functions

Seeking guidance on running mysql queries through JQuery. Any recommendations or tutorials available? I am working on integrating a system with jquery mobile, using a mysql database as the backend. Are there any resources out there to help me understand h ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Choose the default text option for your AngularJS dropdown menu

I am facing an issue with my angularjs dropdownlist that is using ng-options. <select ng-options="perlocation.name for perlocation in locations" ng-model="locationDropdown"> Even though my dropdown list loads correctly, the selected option 0 is dis ...

Steps for running the function saved in variable `x`, with the value `function(){alert('a')}` assigned to it

How can I achieve this using javascript? var x = 'function(){ ... }' x = x.toFunction(); x(); Previously, I used var x = '...'; eval(x), but I have learned that this method is inefficient and slow. To provide some context, my goal is ...

Can the DOM be automatically refreshed after a set period of time without requiring any user input or triggers?

Is it possible to refresh the DOM using a function within a timeout without requiring an event trigger, such as a click? I have divs being inserted by Javascript that I cannot modify, and I need to loop through all of them with a specific class in order t ...

Error message: "Uncaught ReferenceError: $ is not defined in BackboneJS and RequireJS"

In my Backbone application, I am using RequireJS. However, I keep encountering the error message Uncaught ReferenceError: $ is not defined, indicating that my libraries may not be loading properly. This is what my RequireJS config looks like: require.con ...

How can I use lodash to iterate through and remove whitespace from array elements?

I am currently working on a project involving demo lodash functionality, and I have encountered some unexpected behavior. Within an array of cars, there are various non-string elements mixed in. My goal is to iterate through each element of the array, rem ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

What is the process for incorporating Express.js variables into SQL queries?

Recently delving into the world of node.js, I've embarked on a journey to create a login and registration system using express.js, vanilla JS, CSS, HTML, and MySql. Within the following code lies the logic for routing and handling HTTP Post requests ...

Is there a way to navigate through the various components of an OBJ file that has been loaded using OBJMTLLoader

I recently created a building model using 3DS Max, where each room is represented by a modified cube. To load the OBJ file along with its corresponding MTL, I utilized OBJMTLLoader. However, my current challenge lies in highlighting specific rooms based on ...

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

`The header navigation is not responding to window resizing functionality`

I am currently developing a header navigation that consists of a logo on the left side, a profile icon on the right side, and some navigation links in the middle. A left slide menu has been implemented to trigger when the window width is less than 700px. ...

Refresh your inbox after sending a response by leveraging jQuery and AJAX requests

Let's talk about updating the messaging inbox after a user sends a reply, similar to Facebook's system. Here's how my messaging setup is structured: <div class="message_container"> <div class="message_inbox"> <di ...

What's the best way to assign an array of objects to the state in React?

Currently, I am executing an SQL query in my node/express backend and transferring the result to my React front end via JSON. After checking the information using console.log, everything seems to be working correctly. However, I am encountering difficultie ...

Retrieve Browser Screen Width and Height using MVC3 Razor in the View

I am facing a challenge on my website where I need to generate a Bitmap dynamically and ensure it is rendered according to the width and height of the browser so that there are no overflow issues on the page. Although I have successfully created an image ...

casperjs is encountering difficulty locating the id even after setting it

Issue with CasperJS not locating the ID after setting it Casper.then(function () { screenLog(); var id = String("_newid_"); var arrow = this.evaluate(function () { var arrows = document.querySelectorAll('span.select2-selection__a ...

The supported browser is unable to import ES6 modules

Attempting to incorporate moment.js as an es6 module. The most recent version of Chrome is being utilized. Referring to the conversation here, I experimented with the src path (es6) import * as moment from './node_modules/moment/src/moment' A ...