1

Currently, I am trying to make code for a game when, on pointerdown, a progress tag slowly depletes over time and, on pointerup, the progress bar slowly refills from the value it stopped on.

This is my current working logic:

HTML:

<progress id="air" max="100" value="100"></progress>

Javascript:

// Javascript
var air = document.querySelector('#air').value;

function drowning(){
  if (air <= 0){
    console.log("You have drowned");
  } else {
    air--;
  }
};

addEventListener('pointerdown', function() {
  var losingair = setInterval(drowning, 250);            
});

addEventListener('pointerup', function() {
  clearInterval(drowning);
  setInterval(gainingair, 200);
  function gainingair() {
    if (air = 100) {
      clearInterval(gainingair); 
    }
    else {
      air++; 
    }
  }
});   

1 Answers1

1

Instead of assigning document.querySelector('#air').value to air variable, assign just thedocument.querySelector('#air') part. And use air.value to access the value.

Also, you are clearing the intervals in a wrong way. The value returned by setInterval() is used as the parameter for the clearInterval() method.

Here is the working code

var air = document.querySelector('#air');
var losingairInterval, gainingairInterval

function drowning() {
  if (air.value <= 0) {
    console.log("You have drowned");
    clearInterval(losingairInterval);
  } else {
    air.value--;
  }
}

function gainingair() {
  if (air.value == 100) {
    clearInterval(gainingairInterval);
  } else {
    air.value++;
  }
}

addEventListener('pointerdown', function() {
  clearInterval(gainingairInterval);
  losingairInterval = setInterval(drowning, 250);
});

addEventListener('pointerup', function() {
  clearInterval(losingairInterval);
  gainingairInterval = setInterval(gainingair, 200);
});

dispatchEvent(new CustomEvent('pointerdown'))
<progress id="air" max="100" value="100"></progress>
Prakhar
  • 1,445
  • 9
  • 15
  • Thanks Prakhar, just removing `dispatchEvent(new CustomEvent('pointerdown'))` has created the intended effect and jittering. – Cameron Whiting Jul 21 '20 at 13:13
  • @Cameron Whiting The `dispatchEvent` part was just for testing the functionality. I should have stated this in the answer. – Prakhar Jul 21 '20 at 13:17