0

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);
  • 1
    It is counting, but you're only printing the value once. Try putting ```console.log(z)``` inside of ```setInterval``` (make sure you put it before the ```return```. – Carlton Lindsay Nov 03 '21 at 04:36

1 Answers1

2

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.

Steve
  • 4,372
  • 26
  • 37
  • Wow! Thank you so much, did not know JS rounding errors existed [new to JS btw] -- the decimal manipulation you did is pretty creative, I'll keep that in mind for the future! – user17315389 Nov 05 '21 at 03:49
  • No worries, another option would be something like this: `Number((z + increment).toFixed(1))`. toFixed converts it to a string so you just need to cast it back to a number. – Steve Nov 05 '21 at 04:20