Search code examples
javascriptnode.jstimer

NodeJS timer for function that calls itself


I've got a Discord Bot and I want to check the database I'm using every a certain time looking for something. So, I added this on my app.js:

setTimeout(functions.verifyEmptyTeams, 864000)

The thing is that after that time (the time in miliseconds is just for testing) it runs the fuction once and it loops. I added that same line at the end of the function so it does the same on loop. The function is:

    verifyEmptyTeams: function verifyEmptyTeams(){
        console.log('Verifying Empty Teams');
        let getTeams = 'SELECT * FROM teams';
        let i = 0;
        con.query(getTeams, function(err, teamResults){
          if(err) return handleDisconnect();
          for (rowDataPacket in teamResults){
            let teamOwner = teamResults[i].teamOwner;
            let tournamentID = teamResults[i].tournamentID;
            let getPlayers = 'SELECT * FROM players WHERE teamOwner = ? and tournamentID = ?';
            let data = [teamOwner, tournamentID];
            con.query(getPlayers, data, function(err, resultPlayers){
                if(err) console.log(err);
                if(resultPlayers.length == 0){
                    let deleteTeam = 'DELETE FROM teams WHERE teamOwner = ? and tournamentID = ?'
                    con.query(deleteTeam, data, function(err){
                        if(err) console.log(err);
                    })
                }
            })
          }
        })
        setTimeout(verifyEmptyTeams(), 864000)
    }

Edit: Just to be more clear. It loops inmediatly instead of waiting the 15 minutes again.


Solution

  • Your recursive call's syntax is incorrect:

    setTimeout(verifyEmptyTeams(), 864000)
    

    What this does is it invokes verifyEmptyTeams immediately, then passes its return value to setTimeout. You need to pass just the function to setTimeout instead, so that setTimeout can call it:

    setTimeout(verifyEmptyTeams, 864000)
    

    But for longer timeouts like these, it might be more appropriate to use something like node-cron instead.

    cron.schedule('*/864 * * * * *', verifyEmptyTeams);