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