Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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);
        }
    };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
};
about 4 years ago · Juan Pablo Isaza Report

0

Try using setTimeout to execute your main function. Javascript is not supporting any delays as it is single threaded.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!