.setTimeout() inside for loop to update data (mongoDB)

Viewed 33

I'm trying to make the "Bee" to sleep for 5 seconds when it's energy becomes 0, then it'll regains back it's all stats. However, it's stats has became 0 after the command is executed, but after 5 seconds it wouldn't regain back the stats. Any idea how to fix it?

// some codes above (unrelated)
Hive.findOne({ User: message.author.id }, async (err, data) => {
    // some codes here (unrelated)
    const arr = [];
    const en = Object.keys(data.Hives).map((key) => {
        return data.Hives[key].Energy
    })
    for (let a = 1; a < en.length + 1; a++) {
        if (!isNaN(data.Hives[`Hive${a}`].Energy)) {
            data.Hives[`Hive${a}`].Energy -= 1
            if (data.Hives[`Hive${a}`].Energy < 1) {
                arr.push(` Your ${data.Hives[`Hive${a}`].Bee} is out of energy! It's going to sleep.`);
                data.Hives[`Hive${a}`].Gathers = 0;
                data.Hives[`Hive${a}`].Converts = 0;
                // --- where the problem begins ---
                setTimeout(async() => {
                    data.Hives[`Hive${a}`].Energy = data.Hives[`Hive${a}`].MaxEnergy;
                    data.Hives[`Hive${a}`].Gathers = 2.5 * (1 + 0.1 * (data.Hives[`Hive${a}`].Level - 1));
                    data.Hives[`Hive${a}`].Converts = (80 * (1 + 0.1 * (2 - 1)) * statsProfile.ConvertRate) / 100;
                }, 5000);
            // --- where the problem ends ---
            };
        };
    };
    if (arr.length != 0) {
        message.reply({
            embeds: [
                new Discord.MessageEmbed()
                    .setTitle("Out of energy...")
                    .setDescription(arr.join(`\n`))
                    .setColor("ffbe42"),
            ],
        });
    }
    //some codes here as well (unrelated)

    await Hive.findOneAndUpdate(user, data);
});

I've tried putting await data.save() inside and before .setTimeout()

1 Answers

setTimeout is only for delaying the execution of the command. Instead of setTimeout, use setInterval. Then use another function to loop it every 5 seconds.

Here's how I do about the looping function:

function loop() { //added the function for looping
   Hive.findOne({ User: message.author.id }, async (err, data) => {
    // some codes here (unrelated)
    const arr = [];
    const en = Object.keys(data.Hives).map((key) => {
        return data.Hives[key].Energy
    })
    for (let a = 1; a < en.length + 1; a++) {
        if (!isNaN(data.Hives[`Hive${a}`].Energy)) {
            data.Hives[`Hive${a}`].Energy -= 1
            if (data.Hives[`Hive${a}`].Energy < 1) {
                arr.push(` Your ${data.Hives[`Hive${a}`].Bee} is out of energy! It's going to sleep.`);
                data.Hives[`Hive${a}`].Gathers = 0;
                data.Hives[`Hive${a}`].Converts = 0;
                // --- where the problem begins ---
                /*setTimeout(async() => {
                    data.Hives[`Hive${a}`].Energy = data.Hives[`Hive${a}`].MaxEnergy;
                    data.Hives[`Hive${a}`].Gathers = 2.5 * (1 + 0.1 * (data.Hives[`Hive${a}`].Level - 1));
                    data.Hives[`Hive${a}`].Converts = (80 * (1 + 0.1 * (2 - 1)) * statsProfile.ConvertRate) / 100;
                }, 5000);*/
            // --- where the problem ends ---
            };
        };
    };
    if (arr.length != 0) {
        message.reply({
            embeds: [
                new Discord.MessageEmbed()
                    .setTitle("Out of energy...")
                    .setDescription(arr.join(`\n`))
                    .setColor("ffbe42"),
            ],
        });
    }
    //some codes here as well (unrelated)

     await Hive.findOneAndUpdate(user, data);
  });
}

/* Here's when calling the function */
setInterval(() => {
   loop();
}, 5000)

I commented the setTimeout so there's no delay on executing the command, so every 5 seconds the loop() function will execute.

Related