Utilizing a variable that is dynamically calculated within a function and applying it on itself using the

In my Java code, I have a method that calculates the current price, which is then utilized in my JavaScript code provided below.

function updatePrice(id, currentPrice){

var newPrice = 0;
var cPrice = currentPrice;
cPrice = cPrice * 100;
if(rate == 1){
    newPrice = cPrice - 1;
}
if(rate == 2){

    newPrice = cPrice - 2;
}
if(rate == 3){

    newPrice = cPrice - 3;
}
document.getElementById(id).innerHTML = newPrice/100;;
return newPrice / 100;
}



var nPrice = updatePrice('reverse', currentPrice); //The new calculated price, currentPrice is the price first injected into the script 
var timeinterval = setInterval(function() { nPrice = updatePrice('reverse', nPrice); }, 60000); //the nPrice as currentPrice

I aim to leverage the newPrice calculated in updatePrice on itself when executing setInterval, ensuring that every minute the newPrice decreases by 1, 2, or 3 pence accordingly;

There might be a simple solution that has escaped my notice until now.

If this explanation isn't clear, feel free to request more information.

Answer №1

The main issue you are facing is that you have not assigned the return value of updatePrice('reverse', nPrice) to nPrice. Consequently, each iteration will use the same value for nPrice, resulting in the same outcome.

To address this and achieve a decrementing effect, you can update the code as follows:

var nPrice = updatePrice('reverse', currentPrice);
var timeinterval = setInterval(function() { nPrice = updatePrice('reverse', nPrice); }, 60000);

However, there are additional optimizations you can implement in your solution.

function updatePrice(id, currentPrice, rate){
    var newPrice = 0;
    var cPrice = Number(currentPrice) * 100;
    newPrice = ((cPrice - rate) / 100).toFixed(2);
    document.getElementById(id).innerText = newPrice;
    timeout = setTimeout(function () {
        updatePrice(id, newPrice, rate);
    }, 1000);
}

var rate = 1;
var currentPrice = 10;
var timeout = null;
// The newly calculated price, with 'currentPrice' being initially injected from jsp
updatePrice('reverse', currentPrice, rate);
<div id="reverse"></div>

Considering that your desired reduction amount corresponds to the rate, conditional statements to handle different rate values are unnecessary. Simply subtract rate directly from cPrice.

Furthermore, using a recursive setTimeout instead of setInterval eliminates the need to manage global variables or constantly update them.

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

Stopping the page from refreshing on an ajax call in asp.net: a guide

Is there a way to prevent page refresh during an Ajax call? I have multiple views that open when a user clicks on a link button from a tree view. Currently, the views are refreshing the page with each button click. I would like to display a loading image ...

Error: The "require" function is not recognized in this context. (Unknown function) @ ng2-translate.ts:2

Encountering the following error: Uncaught ReferenceError: require is not defined(anonymous function) @ ng2-translate.ts:2 The issue arises from the line where I'm importing @anguar/http import {provide} from '@angular/core'; import {Http ...

How can I verify if an unsupported parameter has been passed in a GET request using Express/Node.js?

Within my node.js backend, there is a method that I have: app.get('/reports', function(req, res){ var amount = req.param('amount'); var longitude = req.param('long'); var latitude = req.param('lat'); var di ...

Gather all information for populating the dropdown menu

I'm trying to fetch data from an API using Vue Form and Axios, but I'm having trouble retrieving it at the moment. I might have missed something. Specifically, I need to retrieve the brand of a car. When a brand is selected in one dropdown, the s ...

React app experiencing issues with onClick button methods not functioning as expected

Here is the React code for a sample homepage. My intention was to have the function run and update the page when the buttons are clicked. However, instead of updating the page, it keeps showing alerts. I have confirmed that the fetch function is pulling da ...

Unable to properly align divs vertically

Having trouble getting some divs to align properly, whether they are in an accordion or not. The current layout is not what I want: My goal is to have them vertically aligned at the top, despite varying lengths. Any help would be appreciated. I attempted ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Saving HTML code entered in a textarea field does not work with the database

Recently, I encountered an issue on my website related to storing news posts in HTML format. My initial approach was to write the posts in HTML for better presentation and then transfer this code into a Textarea element. The plan was to save this input in ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

JavaScript fails to accurately arrange list items

Within my array of objects, I have a list of items that need to be sorted by the fieldName. While the sorting generally works fine, there are certain items where the sorting seems off and does not function properly. Here is the code snippet responsible fo ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

Using three.js lookAt() to align a local axis that is not the positive Z axis towards a different object

Currently, I am in the process of developing an application in which a character (depicted as a cone shape for now) is positioned on a specific surface (currently represented by a cylinder placed horizontally). My goal is to have the character's feet ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

Converting an HTML page into a JSON object by scraping it

Is there a way to convert an HTML page into a JSON object using web scraping? Here is the content of the page: <html><head><title>Index</title><meta charset="UTF-8"></head><body><div><p>[ <a href ...

The .push method in Javascript is failing to execute

I'm facing a challenge with this particular code snippet. Essentially, I am attempting to loop through an array of Word objects and categorize them based on word type using a switch statement. This process is triggered by jQuery listening for a button ...

Executing multiple HTTPS requests within an Express route in a Node.js application

1 I need help with a route that looks like this: router.get('/test', async(req, res)=>{ }); In the past, I have been using the request module to make http calls. However, now I am trying to make multiple http calls and merge the responses ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

Simple code styling tool

Seeking guidance to create a basic syntax highlighter using JavaScript or ClojureScript. While aware of existing projects like Codemirror and rainbow.js, I'm interested in understanding how they are constructed and looking for a simple example. Do th ...