javascriptanimationsetintervalincrementgenerative-programming

JavaScript Counter Variable Fluctuate Between Two Values


I'm trying to fluctuate the variable "z" by 0.1 between the two ranges of 0 and 2 continuously. When it hits the max of 2, I want the variable "z" to decrement. And when it hits the min of 0, I want the variable "z" to increment. So far, all my code does is return the number 1.

NOTE: I'm also using doing this on canvas-sketch by github.com/mattdesl

let z = 1;
let count = 0.1;

setInterval(function(){
  if(z == 2) count *= -1;
  if(z == 0) count *= +1;
  return z += count;
}, 1000);

console.log(z);


Solution

  • Try this:

    let z = 1;
    let increment = 0.1
    
    setInterval(function(){
      if(z === 2) increment = -0.1;
      if(z === 0) increment = 0.1;
      z = Math.round((z + increment) * 10) / 10;
    
      console.log(z);
    }, 1000);
    

    The z line is pretty key here. Try it as just z += increment and you'll get JS rounding errors. So we just need to make sure that we clean the number to one decimal place after adding it.