Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

javascript - Discord.js wait for setTimeout function to finish, before allowing it to run again

I've been trying to figure this out for a while, but nothing seems to be working. Whenever someone tries to use the command pqtimer in the 1 hour period of the timer, I want it to be ignored, since the user should only be allowed to activate the timer when it's finished.

I've read some stuff about async functions, but I couldn't get that to work so I'm not sure if that's even the correct way to solve it.

Would love to get some help on this!

if(command === 'pqtimer') {
        message.channel.send('Patreon quest timer started! (1hr)');
        setTimeout(function(){
            message.channel.send('Time for a new quest!');
            message.author.send(`Time for a new quest!`);
        }, 3600000);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

setTimeout() returns an ID. You could remember this id in some global state and only create a new timeout, when there is no timeoutid in the global state. Don't forget to remove it from the global state, once the timeout callback is executed

let myGlobalState = {
  timeout = 0;
}





if (command === 'pqtimer' && !myGlobalState.timeout) {
  message.channel.send(' ... ');
  myGlobalState.timeout = setTimeout(function() {
     ...
     myGlobalState.timeout = 0;
  }, 3600000);
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...