Mr Questions Mr Questions - 5 months ago 70
Javascript Question

Simplest possible irrevocable timout / cooldown function?

I'm trying to add a 1 second cooldown to my send-message system (as in, you can send 1 message per second max). So my initial thought was simply to create a timeout, and before attempting in sending to check if it exists still. That turned out to take more line of code than I anticipated initially.

Is there something I'm missing here? Isn't there something as simple as:

//inside some message sending function
//send message
mySuperCooldown = cooldown(1000);

Everything else I construct successfully ends up taking loads of lines, and it appears to me as something someone thought of before. Thank you, and excuse my illiteracy.

Answer Source

Have a flag that allows messages, and set it to false when a message is sent. Then set a timeout for 1000 milliseconds that resets the flag to true.

var allowMessage = true;
function sendMessage(msg) {
    if (allowMessage) {
        //do something
        allowMessage = false;
        setTimeout(() => allowMessage = true, 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download