Mugs
Mugs

Reputation: 339

spam asynchronous callbacks breaking my setTimeout delay

So my character div changes its background image when the player presses x which then kills the enemy if the character is touching the enemy. This image switch is to do a mock animation of swinging a sword.

I used set timeout to delay switching the background image back to its original state. This works.

HOWEVER theirs a bug where if I spam x there is no longer a delay between the images switching and I hypothesize the reason having something to do with stacking asynchronous callbacks from the setTimeout function that gets invoked when the player spams x.

** SET TIMEOUT INVOKED IN THIS FUNCTION **

function pressOn(e) {
    e.preventDefault();
    let tempKey = (e.key == " ") ? "space" : e.key;
    keys[tempKey] = true;

         if (keys['x'] && player.swing == false){
              player.plane.style.backgroundImage ='url(guts2.png)';
                 setTimeout(function () {
                 player.swing = true;
                 }, 300);
          }

 }

** REVERTS BACKGROUND IMAGE TO ORIGINAL **

function playGame() {
   if (player.inplay) {

       if (player.swing && !keys['x']){
             player.plane.style.backgroundImage ='url(guts1.png)';
             player.swing = false;
        }

    window.requestAnimationFrame(playGame);
    }
}

** LINK TO JS FIDDLE FULL PROJECT **

https://jsfiddle.net/mugs17/sud2ojxy/17/

Upvotes: 5

Views: 411

Answers (1)

Mugs
Mugs

Reputation: 339

Your logic is backward in setTimeout. You want to set swing equal to true automatically (which will prevent the if statement from executing) and inside the setTimeout callback you set it back to false.

- Heres the solution:

let player = {
       swing: false
}

-

function pressOn(e) {
    e.preventDefault();
    let tempKey = (e.key == " ") ? "space" : e.key;
    keys[tempKey] = true;

    if (keys['x'] && player.swing == false) {

        player.plane.style.backgroundImage = 'url(guts2.png)';
        player.swing = true;

        setTimeout(function () {

            player.plane.style.backgroundImage = 'url(guts1.png)';
            player.swing = false;

        }, 1000);

}

Upvotes: 2

Related Questions