incorporate setInterval() with a dynamic variable serving as the millisecond value

During initialization of the component, a value is fetched from the ngrx store and used as a configuration.

this.storeService.selectMConfig().subscribe(res => {
            if (!res) return;
            const refreshValue = Number(res.items[0].value) * 1000;
            this.intervalValue = refreshValue ?? 10000;
        });

The goal is to pass this value into the setInterval function for customization.

In the initial version, data is fetched every 10 seconds, but the intention is to make it configurable.

In the second version, this.intervalValue is used with a value of 10000. However, an infinite loop is being triggered, and it's unclear why or how to resolve it. Why is it not functioning properly with a variable?

        //v1
        setInterval(() => {
            this.storeService.fetchData(this.payload);
        }, 10000);

        //v2
        setInterval(() => {
            this.storeService.fetchPnrDashboardDetailsForMap(this.mapDetailsPayload);
            console.log('settimeout', this.mapRefreshConfig); // this.mapRefreshConfig = 10000
        }, this.mapRefreshConfig);

Answer №1

Create a control system for intervals that allows you to easily change the function or time as needed. You can also pass variables inside the function. Here is an example:

const customInterval = {
        
    isRunning       : false,
    intervalTime    : 1000,
    customFunction  : false,
    controls        : function(action, value){

        if( action == 'start' ){
            customInterval.controls('stop');
            customInterval.isRunning = setInterval(customInterval.customFunction, customInterval.intervalTime);
        }
        else if( action == 'stop' ){
            clearInterval(customInterval.isRunning);
        }
        else if( action == 'set_time' ){
            customInterval.intervalTime = value;
        }
        else if( action == 'set_function' ){
            customInterval.customFunction = value;
        }
    }
};

// Testing the interval control system -----------------------------------

// Test #1
customInterval.controls('set_time', 1000);
customInterval.controls('set_function', function(){
    console.log('hello');
});
customInterval.controls('start');

// Change the parameters after 5 seconds
// Test #2
setTimeout(function(){
    
    customInterval.controls('set_time', 5000);
    customInterval.controls('set_function', function(){
        console.log('hello world');
    });
    customInterval.controls('start');
}, 5000);

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

When should vuex be used for storing data instead of relying on local component data?

Currently I am tackling a complex project that is built using Vue. Our team has opted to use Vuex as our state management system, however there are certain components where the data is not needed elsewhere. Should I follow convention and store this data ...

I am encountering issues in Vue JS when using ternary expressions alongside v-if statements

Snippet:- <template> <div id="calendars-results"> <div class="vs-con-loading__container"> <div class="vs-row flex justify-between"> <h4 class="vs-row mb-2">{{ title } ...

Changing a JavaScript string into an array

I have extracted an array of objects from a hidden HTML input field and received the following string: "{"id":"1234","name":"john smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0a9b7b3aeb29ab8b6bbb2f4b9b5b7" ...

What could be the root cause behind this Selenium mistake?

My goal is to verify the correct scroll position in the browser using NightwatchJS and Selenium. Below is the command I am using in Nightwatch: assertScrollPosition(testValue) { this.api.execute(() => { const offsetValue = w ...

What is the reason for the absence of Duplex Stream in the Web Streams API?

I have experience working with the traditional nodejs stream, which makes the need for Duplex streams quite evident. These are streams that can both read and write data, like net.Socket. As mentioned here Examples of Duplex streams include: TCP sockets ...

Guide to transforming a vertical tabbed content panel into a responsive collapsible using media queries and jQuery

I am in the process of creating a new content navigation design that incorporates vertically stacked tabs to toggle hidden panels adjacent to the tabs. Unfortunately, this layout seems to encounter issues at narrower screen widths. Check out my work on Fi ...

Preventing Firebase duplicates leads to the error of not being able to read the property 'apps'

Struggling to incorporate Firebase into a TypeScript/NextJS project, I have encountered difficulties. Despite successfully importing and initializing the app: import * as firebase from "firebase/app"; import { collection, getDocs } from "fir ...

Unable to set values to an array of objects in JavaScript

Currently, I am facing an issue in my node.js project where I am unable to assign values to an array of objects. This problem has occurred before, but I just can't seem to figure out the root cause. My suspicion is that it might be related to variable ...

Retrieving and storing information from a form without the need to submit it

I have been given the task of creating a load/save feature for a complex form. The goal is to allow users to save their progress and resume working on it at a later time. After much consideration, I have decided to implement server-side storage by saving ...

Unable to assign focus to textbox

In my chrome extension, I have implemented two text boxes - one for entering a URL and the other for LDAP. Upon clicking on the extension icon, a popup page opens where I automatically fill the URL text box with the current page's URL using the code s ...

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "ä" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

The disabled attribute appears to be ineffective in an Angular reactive form

In my Angular reactive form, I have an email field that I want to disable when the form is in edit mode instead of add mode. The code I am using for this is: disabled: typeof user.user_id === 'string' When I debug the modelToForm method and che ...

AngularJS directive and customized markup/function

Here is the code snippet I am currently working with: <body ng-controller="testController"> <div test-directive transform="transform()"> </div> <script type="text/ng-template" id="testDirective.html"> <div& ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...

Connect Angular Material by chaining together md-select elements from arrays and array of form inputs

I am encountering a challenge with combining chains in Angular Material. I aim to transition from this linked solution on jsfiddle to using md-select and md-option in Material. How should it function? It's quite simple. Here's the scenario: Se ...

Steps for inserting a JSON Array into a database

I have a dropdown menu that displays different options based on the selection from another dropdown. The data for each dropdown is fetched from the database and I need to insert the selected values into a new table in the database. All the necessary code ...

Can we set a restriction on the maximum number of children a particular div can contain?

I'm trying to find a way to restrict the number of children in a div. The concept is that there is a selected commands div where you can drag and drop available commands (essentially buttons) from another div called available commands. However, I wan ...

Images that are automatically generated cannot be interacted with by clicking on them

I currently have 4 images loaded onto my website. Whenever I click on one of the images, it becomes highlighted as desired using the following code: JavaScript Function 1 : var ImageSelector = function() { var imgs = null; var selImg = null; retu ...

Guide to configuring Ionic Auto Height Sheet modal in Vue 3

Trying to implement an Ionic Auto Height Sheet modal in a Vue 3 project (https://ionicframework.com/docs/api/modal#auto-height-sheet). Below is the code I have written. In ion-tab-button #3, I included id="open-modal". Underneath the ion-tab-but ...