Search code examples
javascripttimeoutchatmessage

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.


Solution

  • 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);
    }