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

196
Visualizações
I want to run a function only one time while my condition is true

I have an arry of balls, and I want to add balls to that array when the user clicks space. The problem is that when space button is clicked the conditions stays true 1 to 2 seconds and it creates haundreds of balls instade of only one ball. How can I create only one ball even if the condition is true all the time.

let balls = [
        {
          x: totalWidth / 2,
          y: totalHeight / 2,
          speed: 8,
          size: 20,
          color: 'red',
          leader: true,
        },
      ];
      
window.addEventListener('keydown', function(e) {
          if(e.keyCode == 32) {
            let newSize = (balls[0].size/2);

            let newBall = {
              x: balls[0].x +100,
              y: balls[0].y +100,
              speed: 0,
              size: newSize,
            }

            balls.push(newBall);
            console.log(balls);

            balls.forEach(ball => {
              ball.size = newSize;
            })
          }
        });

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

0

use removeEventListner

const totalHeight = 10;
const totalWidth = 10;
let balls = [
        {
          x: totalWidth / 2,
          y: totalHeight / 2,
          speed: 8,
          size: 20,
          color: 'red',
          leader: true,
        },
      ];
      
const keydownFunction = e => {
    if(e.keyCode == 32) {
      let newSize = (balls[0].size/2);

      let newBall = {
        x: balls[0].x +100,
        y: balls[0].y +100,
        speed: 0,
        size: newSize,
      }

      balls.push(newBall);
      console.log(balls);

      balls.forEach(ball => {
        ball.size = newSize;
      })
      window.removeEventListener('keydown', keydownFunction);
    }
}
      
window.addEventListener('keydown', keydownFunction);

about 4 years ago · Juan Pablo Isaza Relatório

0

If you don't want the keydown event fired multiple times util user release the key. You can check e.repeat at first in your event handler.

Or, if you want the event handler only been invoked once. You can add { once: boolean } parameter for addEventListener.

about 4 years ago · Juan Pablo Isaza Relatório

0

Simplest solution could be to modify your if-statment here:

window.addEventListener('keydown', function(e) {
      if(e.keyCode == 32) {

to

window.addEventListener('keydown', function(e) {
      if(e.keyCode == 32 && !e.repeat) {

The repeat param indicates that certain key was held and in your case we want to perform something only when there was no repeat i.e. e.repeat == false or in short form !e.repeat

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