Search code examples
javascriptnode.jsdiscorddiscord.js

Check how much time has passed since event called (discord.js)


I would like to know how i can check how much time has passed since an event (interactionCreate in my case) was fired, and do something after a certain amount. This is my current code:

  client.once('interactionCreate', interaction => {
                    if (!interaction.isButton()) return;

                    if (interaction.customId == '1') {
                        // do something 
                    } else {
                        // do something else
                    }

                })

It will check which of 2 buttons is pressed, but i also want to check if no button has been pressed in, let's say, 20 seconds, in that case it will do something different like sending a message but most importantly make it unable to interact with the 2 buttons.

How could i do this?


Solution

  • To do something certain time after the event is called, you shoud use setTimeout like this:

    setTimeout(() => {
        // do something after 5 seconds
    }, 5000)
    

    You can create a variable where you store if another button was clicked or not, then, after the timeout, you check if the variable is true or false.

    Your entire logic would look like this:

    let buttonWasClicked = false;
    
    client.once('interactionCreate', interaction => {
        if (!interaction.isButton()) return;
        if(!buttonWasClicked) buttonWasClicked = true;
        if (interaction.customId == '1') {
            // do something 
        } else {
            // do something else
        }
        setTimeout(() => {
            // after waiting 20 seconds
            if(buttonWasClicked) {
                // do something if a button was clicked
            } else {
                // do something if no button was clicked
            }
        }, 20000)
    })