Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a delay between function excutions

I am creating this little chatbox thing with socket.io, and I am wondering how I can add a delay between message sending to prevent spam and such.

Here is my code for sending a message.

    // Sends a chat message
    const sendMessage = () => {
        let message = $inputMessage.val();
        // Prevent markup from being injected into the message
        message = cleanInput(message);
        // if there is a non-empty message and a socket connection
        if (message && connected) {
            $inputMessage.val("");
            addChatMessage({ username, message });
            // tell server to execute 'new message' and send along one parameter
            socket.emit("new message", message);
        }
    };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could add a variable that tracks the time of the most recently sent message and a comparison of this variable and the current time; if the difference is too small, refuse to send it.

Minimal example:

window.lastMessageTime = 0;
function sendMessage(message) {
  if(Date.now() - window.lastMessageTime < 5000)
    return false;
  window.lastMessageTime = Date.now();
  // Proceed
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading