Johnathan Au
Johnathan Au

Reputation: 5362

How to constantly check for new message with setInterval without constantly notifying user?

I have a jQuery AJAX function where I check for new messages and if there are any, I display a notification to the user that they have a new message. My function is getNewMessage(); which for now works perfectly on page refresh because everything happens once. However, when I put it in setInterval("getNewMessage()", 20000), I get an infinite loop of notifications. This is understandable but how do I stop it from notifying the user every time but at the same time keep checking for new messages?

This is my getMessage function, sorry for the big function:

function getNewMessage()
{
    /** Retrieve new messages **/
    $.post('',  { newMessage : true}, function(data)
    {      
        data = $.parseJSON(data);

        /** If new messages exist then display  notification and popup **/
        if(data)
        {

            var newMessageDialog = $('#newMessageDialog');

            /** Create popup dialog options **/
            newMessageDialog.dialog(
            {
                autoOpen: false,
                modal: true,
                minWidth: '100',
                width: '800',
                hide: 'fold',
                show: 'drop',
                title: "New Messages",   
                close: function()
                {
                    hideAllNotifications();
                } 
            });

            /** Initialise variables **/
            var html = '';
            var length = 0;
            var total = 0;

            /** For each message we create the html for the message and insert into dialog **/
            $.each(data, function(name, messages)
            {
                length = messages.length;
                total += length;
                /** For grammatical reasons. If length > 1 then "message" is plural**/
                grammar = (length > 1) ? "messages" : "message";

                /** Reverse the messages so the latest message appears at top and earliest message at bottom **/
                messages.reverse();

                var msgs = '';
                for(var i in messages)
                {
                    msgs += '<p>' + messages[i]['date'] + ': ' + messages[i]['message'] + '</p>';
                }

                html += '<a href="uid[' + messages[i]['uid'] + ']" class="popUpLink">' + name + ': ' + length + ' new ' + grammar + '</a>';
                html += '<div class="popUpDialog" id="viewNewMessageDialog" title="New messages from ' + name + '"><div class="flexi_box"><h3 class="hubHeader">' + name + '</h3>' + msgs + '</div></div>';
                html += '</br>';
            });

            /** Insert Content **/
            $('.flexi_box h3', newMessageDialog).after(html);

            /** Bind dialog to popuplinks **/
            popUpDialogs();

            /** Bind click event
             *  If clicked then we assume message has been read so we delete from messages table **/
            $('a.popUpLink', newMessageDialog).on('click', function()
            {
                /** Get userid from href **/
                var uid = $(this).attr('href');
                var start = uid.indexOf('[');
                var end = uid.indexOf(']');
                uid = uid.slice(start + 1, end);
                removeReadMessages(uid);
            });

            var grammar2 = (total > 1) ? 'messages': 'message'
            var notifier = showNotification('info', '<h3>You have ' + total + ' new ' + grammar2 + '. Click here to view new ' + grammar2 + '</h3>');

            /** Open dialog on click **/
            $('.info').on('click', function()
            {               
                /** Trigger Dialog **/
                $('#newMessageDialog').dialog('open').css('maxHeight', $(window).height()-90);
            });

            return true;
        }
    });//end post   
}

Upvotes: 0

Views: 2092

Answers (3)

Jon Grant
Jon Grant

Reputation: 11530

Create a global variable - an array - and whenever you display a notification, store the messages[i]['uid'] in it. Then when you check again, exclude any that are already in your array.

Upvotes: 0

bart s
bart s

Reputation: 5100

Detect if you have received a new message different from the previous one. Only if there's a new message, show the dialog.

Upvotes: 0

SLaks
SLaks

Reputation: 887413

Instead of calling setInterval, you should call setTimeout to run the function once.
Then, in your AJAX callback, if you didn't get a message, call setTimeout again.

Upvotes: 3

Related Questions