如何在不不断通知用户的情况下使用setInterval不断检查新消息? [英] How to constantly check for new message with setInterval without constantly notifying user?

查看:89
本文介绍了如何在不不断通知用户的情况下使用setInterval不断检查新消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery AJAX函数,用于检查新消息,如果有,我会向用户显示一条通知,告知他们有新消息.我的功能是getNewMessage();,由于所有操作均发生一次,因此它现在在页面刷新上可完美运行.但是,当我将其放在setInterval("getNewMessage()", 20000)中时,会收到无限循环的通知.这是可以理解的,但是如何阻止它每次都通知用户,同时又继续检查新消息?

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?

这是我的getMessage函数,对不起这个大函数:

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   
}

推荐答案

应该调用setTimeout来运行函数一次,而不是调用setInterval. 然后,在AJAX回调中,如果没有收到消息,请再次调用setTimeout.

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.

这篇关于如何在不不断通知用户的情况下使用setInterval不断检查新消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆