简体   繁体   中英

Prevent if statement from running while already running (Vanilla JS)

I have an if statement which looks something like this:

if( extra.RewardId === "idnumberhere") {
        egg.classList.add("bounce");
        setTimeout (() => {
            egg.classList.remove("bounce");
            petEffects.innerText = `Working`;
            petEffects.classList.add("typing");
        }, 3000);
        setTimeout (() => {
            petEffects.innerText = ``;
            petEffects.classList.remove("typing");
        }, 5000);
}

It is a bit longer than this, but the main problem is that it is interrupting itself if I trigger the if statement a second time, too soon.

How would go about making the second instance wait until the first if statement fully runs its course, and those 5000ms pass before the next instance begins?

EDIT

https://jsfiddle.net/d2jhmec1/2/

I have made a safe to share JSfiddle. Clicking the button will show what I'm currently working with. When clicked twice, it breaks.

You should be able to set a Boolean flag that will tell you whether to run the code or not.

Something like this:

let canAddBounce = true;
let canRemoveBounce = true;

if(extra.RewardId === "idnumberhere") {
    if (canAddBounce) {
        canAddBounce = false;
        egg.classList.add("bounce");
        setTimeout (() => {
            egg.classList.remove("bounce");
            petEffects.innerText = `Working`;
            petEffects.classList.add("typing");
            canAddBounce = true;
        }, 3000);
    }
    if (canRemoveBounce) {
        canRemoveBounce = false;
        setTimeout (() => {
            petEffects.innerText = ``;
            petEffects.classList.remove("typing");
            canRemoveBounce = true;
        }, 5000);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM