简体   繁体   English

防止 if 语句在已经运行时运行(Vanilla JS)

[英]Prevent if statement from running while already running (Vanilla JS)

I have an if statement which looks something like this:我有一个看起来像这样的if语句:

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.它比这长一点,但主要问题是如果我第二次触发if语句,它会中断自己,太快了。

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? go 如何让第二个实例等到第一个if语句完全运行,并且在下一个实例开始之前通过这 5000 毫秒?

EDIT编辑

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

I have made a safe to share JSfiddle.我已经安全地分享了 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.您应该能够设置一个 Boolean 标志,它会告诉您是否运行代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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