The rate of increase decreases as the value approaches its maximum assignment

Visualizing this question requires some pseudo-code, so here it is:

Imagine I have two integers - one variable and one constant.

int current = 0; static int max = 20

My goal is to add slowly as I approach 20, never actually reaching it. For example, if adding 2 takes 3 seconds, the next addition of 2 should take twice as long, and so on.

How can I achieve this gradual increase in time for each addition while approaching 20? Apologies if this is unclear, but I tried my best to explain it :(

Thanks a lot, and wish you a wonderful day!

Answer №1

Let's dive into an interactive example.

function dynamicInterpolator(rate, speed){
  speed = +speed || 1;
  var start = Date.now();
  
  return function(a, b){
    var time = (Date.now() - start);
    var t = Math.pow(1-rate, time * speed/1000);

    return a*t + b*(1-t);
  }
}

var start = Date.now();
var interpolate = dynamicInterpolator(1/16, 1/10);

var output = document.getElementById("output");

function update(){
  var a = 0, b = 100, c = interpolate(a, b);
  output.innerHTML = a + " .. " + Math.floor(c) + " .. " + b + "<br> actually: " + c + "<br>runtime: " + (Date.now() - start)/1000 + "s";

  requestAnimationFrame(update);
  //or
  //setTimeout(update, Math.random() * 500); 
  //because update interval doesn't matter
}
update();
<div id="output"></div>

In reality, the code may reach the end eventually due to the finite precision of Numbers in JS.

Answer №2

To calculate the final amount, you can utilize the following formula:

A = Pert

Here, A represents the resulting amount; P is the initial principal amount; e is Euler's Number, approximately 2.718281828459045; r denotes the interest rate as a decimal; and t stands for the time in years, usually divided by 360.

If the starting principal is 0, the result would also be 0 since no interest can accumulate on a principal of 0. To begin with a nominal value of .01, update the principal to include the accrued interest.

In javascript, you can employ a do..while loop to compute the new principal. Set the loop limit at half the initial rate, or .05/2. Inside the loop, create an immediately invoked function expression to pass the current principal, push a function that returns a Promise after either current or current * duration, where duration is a positive integer. Use Array.prototype.reduce() to execute functions sequentially, increasing the duration of each setTimeout call based on the current principal or current * duration.

You can also modify the formula to incorporate continuous compounding:

A = Per(t/n)

For instance, when setting n to 360, continuously compound interest from a principal of 1 at a rate of .05 over one fiscal year (360 iterations) would yield incremental results leading up to 1.0512710963760241, with a total interest accumulation of .0512710963760241.

Calling the compound function with 1 as input will return 1.0512710963760241.

var current = 0; // principal
var max = 20; // maturity, in years
var rate = .05; // annual rate as decimal
var time = 1; // time in years, alternatively `1/360`
var N = 360; // fiscal year
var arr = []; // store functions which return a `Promise`
var duration = 500;
var output = document.querySelector("output");

function compound(p, r, t) {  
  return ((p||.01) * Math.exp(r * t)); // or `Math.exp(r * (t/N))` 
}

do {
  current = compound(current, rate, time);
   (function(curr) {
    arr.push(
      function() {
        return new Promise(function(resolve) {
          setTimeout(function() {
            output.innerHTML += `current principal: ${curr}<br>`;
            resolve();
          }, curr * duration)
        })
      }
    )
   })(current)
} while (current < max - (rate / 2));

arr.reduce(function(promise, next) {
  return promise.then(next)
}, Promise.resolve())
.then(function() {
   output.innerHTML += `<br>max - current: ${max - current}`; 
});
<output></output>

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

Unexpected token . encountered in Javascript: Uncaught Syntax Error. This error message is triggered when

As someone who is completely new to programming, I was given the task of creating a voting website for a class assignment. In order to store data locally, I managed to create variables and implement them using local storage: var eventName = document.getEl ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Attempting to assign a thumbnail image to a file on Google Drive by utilizing JavaScript

I've been working on adding thumbnails to the files that I upload to Google Drive using Javascript. I'm following the instructions outlined at https://developers.google.com/drive/v3/web/file#uploading_thumbnails For my web-safe base64 image, I c ...

The basic structure for organizing components and categories

I am working on creating a list and have designed the following Schema: new SimpleSchema({ element: { type: String, optional: true }, note: { type: String, optional: true }, order: { type: Number, optional: true } }); Now, I wan ...

Having trouble with sslforfree on Node.js Express.js platform

When attempting to set up an HTTPS server using Node.js and Express.js with sslforfree, I encounter an error 403: access denied when trying to access https://localhost. My folder structure looks like this: https://i.sstatic.net/NZqZT.png Below is my serve ...

Issue encountered while attempting to retrieve data from a local json file due to Cross-Origin Resource Sharing

I'm attempting to fetch and display the contents of a JSON file on a webpage, but I'm encountering this error message: Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

Guide to implementing a random number generator within a Jquery conditional statement

I am experimenting with if statements, but I'm encountering some difficulties. My goal is to assign random numbers to a variable and then trigger different actions based on a click event. Here's what I've tried so far, but it seems to be fa ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

Module not found: The system encountered an error and was unable to locate the file 'os' in the specified directory

I'm currently working on a Laravel/Vue3 project and ran into an issue. When I try to execute "npm run dev", I encounter 37 error messages. I suspect it has something to do with the mix or webpack configuration, but being unfamiliar with this area, I&a ...

Missing RequestVerificationToken value when hiding HTML element using jQuery

I am encountering an issue with my ASP.NET MVC 4 form that involves checkboxes being used to show and hide certain HTML elements. When I initially visit the form page, the RequestVerificationToken value is correctly created as a hidden field. Some HTML ele ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

Displaying Multiple HighCharts on a single AngularJS page

As a beginner with HighCharts, I am working on adding two Highcharts to the same page that will access the same data source but display different pieces of data for each graph. For example, the categories will remain constant while the series[] will vary. ...

JavaScript - Unexpected fluctuations in variable values

After studying Japanese language, I decided to try my hand at experimenting with JavaScript by creating a simple FlashCard game for a project. The game generates an array of random numbers, fills the divs with 6 possible choices using jQuery, randomly sele ...

Error message: "The use of Vue 3 refs in the render function is

I am facing an issue with my Vue component wherein the root element is set as ref="divRef". Strangely, when I try to access divRef.value inside the onMounted function, it returns undefined. Any assistance on this matter would be greatly appreci ...

How can AJAX be used to execute a PHP script that deletes a record from a database table?

Yesterday, I asked for help on how to save user-generated blog posts and I successfully tackled the database aspect of it. Now, my next goal is to be able to delete a blog post upon clicking a button with an onclick event. After researching extensively onl ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

Developing a custom directive that utilizes a dynamic ng-options configuration

Alright, let me share with you my personalized directive: angular.module('bulwarkWebControls', []) .directive('customDropdown', [ function() { return { scope: { label: '@', // can be om ...

Turn on/off the webGL Context in webGL/three.js

I am currently working on an exciting project using three.js, and so far everything is going according to plan. The project involves displaying various meshes in different canvases, which has led me to encounter a particular issue. My goal for the project ...