saibot-tsch
saibot-tsch

Reputation: 121

JS: Chat Timeout Functionality after X messages in a timeframe

So I have to make a chat spam functionality. When the user send a message I want to check if it's the 15'th message the user sent in a 30 second timeframe. If yes I want to give the user a "Timeout" for 1 minute so he can't write anymore messages.

I'v struggled with this for a while now and can't find a good best practice answer. Thanks in advance.

Upvotes: 1

Views: 173

Answers (2)

saibot-tsch
saibot-tsch

Reputation: 121

I worked it out. Here is my solution:

var chatIsTimedOut = false;
var canWrite = true;
var msgsIn30s = 0;
var chatMsgStarted = false;

function addMsg() {
    if (msgsIn30s > 4 && canWrite) {
        console.log("timeout begin");
        canWrite = false;
        chatIsTimedOut = true;
        setTimeout(() => {
            canWrite = true;
            chatIsTimedOut = false;
            msgsIn30s = 0;
            console.log("tmieout away");
        }, 60000);
    } else if (canWrite) {
        msgsIn30s++;
        if (!chatMsgStarted) {
            chatMsgStarted = true;
            setTimeout(() => {
                chatMsgStarted = false;
                msgsIn30s = 0;
            }, 30000);
        }
    }

    console.log("Msgs: ", msgsIn30s);
    console.log("Can Write: ", canWrite);
}

Upvotes: 1

Lcf.vs
Lcf.vs

Reputation: 1842

const contexts = new WeakMap()

const onSubmit = event => {
  const { target } = event
  const context = contexts.get(target)
  const now = Date.now()

  event.preventDefault()
  
  if (context.timeout > now) {
    return
  }

  context.timeout = now + 60000
  // fetch
}

contexts.set(form, { timeout: 0 })
form.addEventListener('submit', onSubmit)

And, into the context, you can also store a messages counter, etc., to be able to test it into your listener.

Upvotes: 0

Related Questions