How to exponentially increase the speed of a variable’s value change?

Asked

Viewed 96 times

1

I want to exponentially increase the speed of changing the value of a variable. I tried to do this, but it didn’t work. When trying to do this, I used 2 setInterval, but it didn’t work. In the code below I tried to increase the speed in the change of the value of variable x, but it didn’t work very well. I would like you to help me and I would also like to know how I do to exponentially increase the value change speed of variable x.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>
    <p id="vel"></p>
    <script>

      var x = 100;
      var y = 1000;
      document.getElementById("vel").innerHTML = x;

      var exponencial = setInterval(function() {
         y -= 2*pow(2, 4);
      }, 1000);

      var time = setInterval(function() {
         x += 1;
         document.getElementById("vel").innerHTML = x;
      }, y);

    </script>
  </body>
</html>

1 answer

0


I think you want it. But don’t use setInterval, use setTimeout. Starting with 1 second (1000 milliseconds) decreases the time by 10 milliseconds (you can adjust).

Create a function that is called each time, with the time value decreased by 10 milliseconds, increasing the speed.

Run the code below and see that in a few moments the speed increases:

function tempo(y){
   y -= 10;
   var time = setTimeout(function() {
      x++;
      document.getElementById("vel").innerHTML = x;
      tempo(y);
   }, y);
}

var x = 100;
var y = 1000;
document.getElementById("vel").innerHTML = x;
tempo(y);
<p id="vel"></p>

  • 1

    It is worth remembering that the method pow that he’s calling is wrong, the correct is Math.pow().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.