Home > Software engineering >  I want to run a function only one time while my condition is true
I want to run a function only one time while my condition is true

Time:05-23

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;
            })
          }
        });

CodePudding user response:

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);

CodePudding user response:

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.

CodePudding user response:

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

  • Related