最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jqueryjavascript setInterval - Stack Overflow

programmeradmin2浏览0评论

Currently I'm developing a user notification alert message function.

I managed to use setInterval to control my Ajax call (to check if there's any notification msg for the user). But my problem is that I only wanted the notification message only appear once on the page (Now it displays multiple notification alert msg on the screen). I know that you can use setTimeout to make it only call once but I also needed the page to check if there's a new notification message alert in every 5 min.

Second question is it possible the first round calling the Ajax call instantly and then all other calls every 5 min? Because I wanted the system to check instantly once they logged into the system n then afterward every 5 min.

Here is my code

function getAjaxNotice() {
    $.post("/async/getnotification", {},
        function(response) {
            var notice = $(response);
            $("#notices").prepend(notice);
        });

    return false;
}

setInterval("getAjaxNotice()", 50000);

Currently I'm developing a user notification alert message function.

I managed to use setInterval to control my Ajax call (to check if there's any notification msg for the user). But my problem is that I only wanted the notification message only appear once on the page (Now it displays multiple notification alert msg on the screen). I know that you can use setTimeout to make it only call once but I also needed the page to check if there's a new notification message alert in every 5 min.

Second question is it possible the first round calling the Ajax call instantly and then all other calls every 5 min? Because I wanted the system to check instantly once they logged into the system n then afterward every 5 min.

Here is my code

function getAjaxNotice() {
    $.post("/async/getnotification", {},
        function(response) {
            var notice = $(response);
            $("#notices").prepend(notice);
        });

    return false;
}

setInterval("getAjaxNotice()", 50000);
Share Improve this question edited Feb 17, 2014 at 13:43 Fedor 1,5783 gold badges29 silver badges39 bronze badges asked Mar 30, 2011 at 17:34 user648198user648198 2,0204 gold badges19 silver badges26 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 11

First of all, you should wrap your initialization code in an onLoad function:

$(document).ready(function() {
  // Put all your code here
});

Making it appear once is easy, use .html() instead to set the content rather than add to it:

$("#notices").html(notice);

Third, as a style note, you should not pass a string to setInterval(). Rather, pass a function name:

setInterval( getAjaxNotice, 50000 );

Finally, to make it call the function now, and again after every 5 minutes, use:

// Set the timer
setInterval( getAjaxNotice, 50000 );
// Call it once now
getAjaxNotice();

Also note that 50000 is 50 seconds, not 5 minutes. 5 minutes would be 5 * 60 * 1000 = 300000.

For the first problem, you should be storing the return value from setInterval, and then calling clearInterval(myIntervalId) when you receive an alert.

For the second problem, you can call getAjaxNotice once during onload of the body, and then if no alerts are received, call setInterval at that point.

setInterval's time is in milliseconds.

5 minutes * 60 seconds * 1000 milliseconds = 300000ms

Also, I suggest you pass a function to setInterval not a string, so you can avoid the implicit use of eval.

setInterval(getAjaxNotice, 300000);

To call getAjaxNotice at the start of the page, put it in a ready block.

$(function(){
    getAjaxNotice();
});

A couple of things...

setInterval("getAjaxNotice()", 50000);

Is not 5 minutes.

5 minutes = 300000 milliseconds.

and if you want it to run instantly and THEN do it every 5 minutes you can simply do

$(document).ready(function() {
     getAjaxNotice();



        function getAjaxNotice() {
             $.post("/async/getnotification" , 
             {},                              
             function(response)
             {
                  var notice = $(response);
                  $("#notices").prepend(notice);
             });
             return false;                      
       } 

       setInterval( getAjaxNotice(), 300000 );

});

In your situation it sounds like you are dealing with a few problems. So using your current approach, you can initially make your ajax call and follow it up with a set timeout:

getAjaxNotice();
setTimeout( "getAjaxNotice()", 300000);

Secondly, ensuring the user received the message only once can be done easily if you have some type of "message confirmed" event. Assume your user could have browsers open on multiple computers, if you make the user click the message or click an ok button, or perform some action to acknowledge they received the message, you can fire off another ajax call to delete that message from the buffer on your server, yet still display it on all open browsers. The local browser would only display it once because you could prevent displaying it client side if the message is a duplicate (based on what ever criteria makes sense for your application)

However, you should look into long polling and COMET, http://en.wikipedia.org/wiki/Comet_(programming). Comet is a concept around pushing notifications to web browsers based on server side events, as opposed to web browsers constantly asking the server for changes.

Due to limitations in web frameworks and browsers, this was accomplished with a few technologies, but long-polling seems to be the most prevalent. HTML5 and websockets are trying to make some changes that could prevent polling all together, but its not readily available yet.

Long Polling, http://en.wikipedia.org/wiki/Push_technology, and COMET based architecture have been used by companies like meebo and facebook. Don't quote me on this but for some reason I'm inclined to believe facebook uses an Erlang based webserver to serve their chat messages. Erlang and NodeJs are just a couple of solutions you can use to build light weight web servers that work well with tons of long polling requests hitting your servers.

You should definitely go read up on all these things yourself as there is a wealth of information available. I have experimented with create a NodeJs server on Amazon EC2, as I'm traditionally a .NET job and don't feel IIS is the right solution for supporting an the long polling features of a .net application which uses long polling, and I have to say I like NodeJs alot. Plus the javascript language is much more familiar to me than my limited knowledge of Erlang.

发布评论

评论列表(0)

  1. 暂无评论