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

105
Visualizações
Why is setInterval not letting my other functions run?

let paddleWidth = 100;
let paddleHeight = 25;
let paddlePositionX = 200
let paddlePositionY = 200

let ballPositionX = canvas.width /2; //ball position on x
let ballPositionY = canvas.height -150; //ball position on y
let dx = 5; //shift along x
let dy = 5; //shift along y

function drawPaddle(){
    ctx.beginPath();
    ctx.rect(paddlePositionX, paddlePositionY, paddlePositionY, paddleHeight);
    ctx.rect(200, 200, 100,25)
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}
drawPaddle()

function drawBall(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.beginPath();
    ctx.arc(ballPositionX, ballPositionY, 15, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();

    ballPositionX += dx;
    ballPositionY += dy;

    if(ballPositionX >= canvas.width || ballPositionX + dx < 0){
        dx = -dx;
    } 
    if(ballPositionY + dy > canvas.height || ballPositionY + dy < 0) {
        dy = -dy;
    }
}
setInterval(drawBall, 10) 

I have two functions, one moving a ball randomly and one is supposed to be a paddle on the screen, now in order to move the ball I am calling drawBall with setInterval. The problem is my paddle does not show on screen and if I comment out the setinterval it shows on screen but my ball disappears.

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

0

Your drawBall method starts by clearing the canvas, so after you have drawn your paddle, the interval will clear it 10ms later. Fix this by removing the clearRect call from your drawBall function and re-drawing the paddle in every loop:

setInterval(() => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawPaddle();
    drawBall();
}, 10)
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