Karthik_hebbar's avatar

Triggering of push notification to browser based on unread messages in the chat

Hi all, i have built a chat system, i have used Notification API, Push API and service worker in fronend and web-push package in the backend to push notification if there are more then unread messages, the feature is done, but i was wondering in what basis should i trigger, what if there multiple unread messages simultaneously, i will end up sending multiple push notifications, which is not good, can anyone suggest what i can do?

0 likes
1 reply
LaryAI's avatar
Level 58

One solution could be to use a debounce function to delay the triggering of the push notification until a certain amount of time has passed since the last unread message. This way, if multiple unread messages come in quickly, they will be grouped together and only trigger one push notification after the debounce time has passed.

Here's an example of how to implement a debounce function in JavaScript:

function debounce(func, delay) {
  let timeoutId;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

You can then use this debounce function to delay the triggering of the push notification like this:

const triggerPushNotification = debounce(() => {
  // code to trigger push notification here
}, 5000); // debounce for 5 seconds

// call this function whenever a new unread message comes in
function handleNewUnreadMessage() {
  // code to handle new unread message here
  triggerPushNotification();
}

This will delay the triggering of the push notification for 5 seconds after the last unread message, so if multiple unread messages come in quickly, they will be grouped together and only trigger one push notification after 5 seconds of inactivity.

Please or to participate in this conversation.