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

237
Visualizações
Why does the global variable gets value NaN? Solved Thank you Everyone
const canvas = document.querySelector('#canvas')
    const context = canvas.getContext('2d')
    let rectX = 0 ;
    let rectY = 0;
    let secondsPassed = 0;
    let timeStamp = 0
    let oldTimeStamp = 0;
    let movingSpeed = 50;
    gameLoop()
    function draw() {
        context.fillStyle = 'red';
        context.fillRect(rectX, rectY, 150, 100);
    }

    function gameLoop(timeStamp) {
        // Calculate how much time has passed
        secondsPassed = (timeStamp - oldTimeStamp) / 1000;
        oldTimeStamp = timeStamp;
        update(secondsPassed);
        draw();

        window.requestAnimationFrame(gameLoop);
    }

    function update(secondsPassed) {
        rectX += (movingSpeed * secondsPassed);
        rectY += (movingSpeed * secondsPassed);
    }

rectX and rectY initially have a number value, movingSpeed also has a number value, secondsPassed as well.My question is why the function "update" gives NaN to the variables rectX and rectY ? No errors are shown in console. I tried to log and used typeof to check if every variable had a value with a type number and I noticed that rectX is once considered a string, I tried to parseFloat the rectX but still it was giving me NaN. Normally, we use timeStamp to return a value that can help us calculate the fps. In this case I'm using timeStamp to see how many seconds have passed before running the function gameLoop. I'm doing this because it's no longer the frame rate (and hardware) that decides the speed of the game, but it's time.

Update: is solved thanks to @epascarello, @James and @Kaiido. There's the updated code for you guys:

const canvas = document.querySelector('#canvas')
    const context = canvas.getContext('2d')
    let rectX = 0;
    let rectY = 0;
    let secondsPassed = 0;
    let oldTimeStamp = 0;
    let timeStamp = 0
    let movingSpeed = 50;
    let timePassed = 0
    function draw() {
        context.fillStyle = 'red';
        context.fillRect(rectX, rectY, 150, 100);
    }

    function gameLoop(timeStamp) {
        // Calculate how much time has passed
        secondsPassed = (timeStamp - oldTimeStamp) / 1000;
        oldTimeStamp = timeStamp;

        // Pass the time to the update
        update(secondsPassed);
        draw();

        window.requestAnimationFrame(function(timeStamp){gameLoop(timeStamp)});
    }

    function update(secondsPassed) {
        // Use time to calculate new position
        rectX += (movingSpeed * secondsPassed);
        rectY += (movingSpeed * secondsPassed);
        
        
    }
    window.requestAnimationFrame(function(timeStamp){gameLoop(timeStamp)});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

your problem is let rectX; in line 3 creates an "undefined"

if you use rectX += 1 js tries to add undefined + 1 (automaticly string converting from undefined)

sting + int = NaN

let rectX = 0;
let rectY = 0;
let speed = 1;
function update(seconds){
  rectX += (speed * seconds);
  rectY += (speed * seconds);
}

// test:

update(5);
console.log(rectX, rectY); // output is 5 5
about 4 years ago · Juan Pablo Isaza Relatório

0

The problem is that you're not passing timeStamp into the gameLoop function when you call it initially. inside gameLoop, timeStamp is undefined, which breaks the other variables.

You could pass in the current time stamp when you first call it. Instead of gameLoop() try

gameLoop(Date.now().getTime())
about 4 years ago · Juan Pablo Isaza Relatório

0

intitialing the variable rectX and rectY might help.

try this:

rectX = 0;
rectY = 0;
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