sengjung123
sengjung123

Reputation: 3

how to get time remaining in an async settimeout?

I am having trouble with getting information on the remaining time left on a cooldown. Specifically, when a user runs a command, the timeout kicks in to prevent any other inputs.

const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
    setTimeout(() => {
        cb();
        resolve();
    }, timeout);
});
const doStuffAsync = async () => {
    await setAsyncTimeout(() => {
        isReady = true;
        console.log("Cooldown finished.");
    }, 60000);};

twitch.on('message', (channel, tags, message, self) => {
    if (isReady){
        isReady = false;
        console.log("running command");
        doStuffAsync();
    }
    else if (!isReady){
        console.log("Not Ready Message should come up here");
    } return;
});

I am trying to let the bot reply to another user on the remaining cooldown time in addition, but I'm unable to do so. Can anyone guide me on the right path to get started?

Upvotes: 0

Views: 161

Answers (1)

AKX
AKX

Reputation: 168957

Don't use setTimeout – just keep track of the time when the thing was last done.

let lastInvocationTime = 0;

twitch.on("message", (channel, tags, message, self) => {
  const now = +new Date();  // get current clock time as milliseconds
  const timeSinceLastInvocation = now - lastInvocationTime;
  if (timeSinceLastInvocation > 60000) {
    console.log("running command");
    lastInvocationTime = now;
  } else {
    console.log(`Sorry, only ${timeSinceLastInvocation / 1000} seconds have passed since the last run.`);
  }
});

Upvotes: 6

Related Questions