Ways to incorporate a pause between functions being executed

I'm working on a chatbox feature using socket.io and I'm interested in adding a delay between message sending to prevent spam. Can someone provide guidance on how to achieve this?

Below is the code snippet for sending a message in my project:

// Function to send a chat message
const sendMessage = () => {
    let message = $inputMessage.val();
    // Cleanse input to prevent markup injection
    message = cleanInput(message);
    // Check if there is a non-empty message and an active socket connection
    if (message && connected) {
        $inputMessage.val("");
        addChatMessage({ username, message });
        // Instruct server to handle 'new message' event and pass one parameter
        socket.emit("new message", message);
    }
};

Answer №1

To prevent sending messages too frequently, you can implement a variable that keeps track of the time when the last message was sent. By comparing this time with the current time and setting a minimum time difference, you can control the rate at which messages are sent.

Here is a simple example:

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

Answer №2

Consider implementing setTimeout to run your primary function. Since Javascript is single threaded, it does not support delays.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the Three JS raycaster to detect intersections as the mouse cursor moves around

I have a strong intuition that the current method I am using is completely off base because I am struggling to achieve optimal performance for my website. Take a look at the primary code snippet: onDocumentMouseMove( event ) { if ( this.isUserInterac ...

Disable the meta tags in Zurb Foundation 5

I have searched extensively online but haven't been able to find a solution for this issue. How can I disable these zurb foundation 5 meta tags in the <head>: <meta class="foundation-mq-small"> <meta class="foundation-mq-small-only"> ...

What methods do Google and Facebook use to manage user sessions effectively?

I'm looking to incorporate a session in my asp.net application that remains active until the user logs out. I've come across this feature on websites like Google, where the session persists even after a computer restart. How do they achieve this ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

There is an abundance of brief PHP documents

After conducting some initial research, I have realized that I need more information on the topic at hand. My interactive website relies on ajax calls to retrieve data from the server. Authenticated users engage with this data through various actions, whic ...

I'm curious why I can only see the HTML code and not the three.js code as well

I attempted to run a sample three.js game today, but only the HTML code appeared. I've also installed three.js with npm and tried running it with the VSC Live Server, but it's not working. You can find the source code here. What should be my nex ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

Works perfectly in Firefox, experiencing glitches in Chrome

After creating a page that utilizes a simple JSon table and JS/JQ to display data, I noticed a slight bug in Chrome when the files were separated into HTML, CSS, JS, and JSON components. The page works perfectly in both Chrome and FF when hosted together o ...

Prevent drag and drop functionality in QtWebkit

As I work on creating an HTML GUI for my application using Qt's WebKit, everything is going smoothly with one minor issue. I am trying to prevent users from dragging and dropping images from the GUI itself. While I have successfully disabled text sele ...

Running ASP.Net with HTML5 JS and Twitter Bootstrap produces a unique design

During development, everything appears to be working fine in my environment. I have a pie chart that uses canvas and animation, and it displays correctly when hosted through the browser. Additionally, I am utilizing Twitter Bootstrap and have a navigation ...

The request for `/` cannot be fulfilled while serving an Angular application with Express and Node.js

I've been attempting to host an Angular application using Node.js, but I keep encountering the error message "Cannot GET /" displayed on the page. Despite trying various solutions, I have been unable to resolve this issue. Does anyone have any suggest ...

How can input be prevented on keydown within angular6?

Is there a way to disable the input field only when a keydown event occurs, without affecting other input fields? xyz.component.html <input type="text" (keydown)="disableInput($event)"> // <-- Disable if keydown <input type="text" (keydown) ...

What is the best way to detect the window scroll event within a VueJS component?

Looking to capture the window scroll event in my Vue component. This is what I have attempted so far: <my-component v-on:scroll="scrollFunction"> ... </my-component> I have defined the scrollFunction(event) in my component methods, but it ...

Having issues with the $addToSet method in my MongoDB API implementation

Despite searching through various topics, I couldn't find a solution to my specific problem. In an effort to enhance my JavaScript skills, I embarked on creating a quote generator. I successfully developed the API and frontend components. However, c ...

"Figuring out a way to include a link with each image in a react-s

I am currently working on a project in Gatsby and encountering some issues with the homepage banner. I am using react-slick which seems to be functioning fine, but when I try to add content on top of each image, it causes some problems. Specifically, setti ...

The functionality of scope.$observe is unavailable within an AngularJS Directive

Consider the snippet below: appDirectives.directive('drFadeHighlight', ['$animate', '$timeout', function ($animate, $timeout) { return { scope: { isWatchObject: '=' }, restric ...

Customize Nivo LightBox to apply to only one video separately on the page

I've recently implemented the Nivo LightBox script on my website for a video popup effect. However, as a newcomer to jQuery, I'm struggling to customize the lightbox to only trigger when clicking a specific link for my video, rather than every li ...

Exploring the world of Restify: Mastering the art of sending POST

Having trouble reading the body of a request while trying to create an API with Restify. Snippet from main.js: 'use strict'; const perfy = require('perfy'); perfy.start('startup'); const restify = require('rest ...

Unable to create a post request using jQuery with a JSON payload

When using the Chrome REST service, I successfully make a post request to a specific URL by sending a JSON string in the body and setting the content type as application/json. However, when trying to achieve the same with jQuery, I encounter some issues. ...

Nodemailer fails to send out emails despite the absence of any error messages

I'm currently working on setting up a confirmation email feature for user sign-ups on my website. I've tackled similar tasks in the past, but this time I've hit a roadblock - the emails are not being sent, and there are no error messages to ...