我有一个 jQuery AJAX 函数,我可以在其中检查新消息,如果有的话,我会向用户显示他们有新消息的通知。我的功能是getNewMessage();
现在在页面刷新时完美运行,因为一切都发生一次。但是,当我把它放进去时setInterval("getNewMessage()", 20000)
,我会收到一个无限循环的通知。这是可以理解的,但我如何阻止它每次都通知用户但同时继续检查新消息?
这是我的 getMessage 函数,对不起这个大函数:
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
}