Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda