Search code examples
javascriptarraysobjectintegertimeout

Integer in object inside array not decreasing


I made this code that when run adds one value to the mzone to a maximum of 3, and that five seconds later should decrease the value that was added, but this last part isn't working. I am still learning so I don't know what might be wrong.

    clubsList[playerCountry].mzone = (clubsList[playerCountry].mzone + 1) || 1; //This works perfectly. It adds 1 to the mzone everytime it's run.
    console.log(clubsList[playerCountry].mzone)
    setTimeout(function(){ (clubsList[playerCountry].mzone - 1 ) }, 5000); //This isn't working
    setTimeout(function(){ (console.log(clubsList[playerCountry].mzone)) }, 6000);

The completed code:

clubsList = []

onNet('verifyMeetingZone', (playerCountry) => {
    if (!clubsList[playerCountry]) {
        clubsList[playerCountry] = {}
        clubsList[playerCountry].mzone = 0
    }
    // HERE
    if (clubsList[playerCountry].mzone <= 2) {
        console.log("Mzone Criado")  
        clubsList[playerCountry].mzone = (clubsList[playerCountry].mzone + 1) || 1; 
        console.log(clubsList[playerCountry].mzone)
        setTimeout(function(){ (clubsList[playerCountry].mzone - 1 ) }, 5000);
        setTimeout(function(){ (console.log(clubsList[playerCountry].mzone)) }, 6000);
    }
    else {
        console.log("Ja existe")  
    }
})

Solution

  • I think you are not re-assigining the changed value back to the object is why the object is not picking up the decrement:

     setTimeout(function(){ clubsList[playerCountry].mzone = clubsList[playerCountry].mzone - 1  }, 5000);
    

    Try this out, it should fix the problem.