Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

intitialing the variable rectX and rectY might help.

try this:

rectX = 0;
rectY = 0;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda