jquery/javascript setInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5489917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:22:21  来源:igfitidea点击:

jquery/javascript setInterval

javascriptjquery

提问by user648198

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

目前我正在开发用户通知警报消息功能。

I managed to use setIntervalto 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 setTimeoutto 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.

我设法用来setInterval控制我的 Ajax 调用(检查是否有用户的任何通知消息)。但我的问题是我只希望通知消息只在页面上出现一次(现在它在屏幕上显示多个通知警报消息)。我知道您可以使用setTimeout它只调用一次,但我还需要该页面来检查每 5 分钟是否有新的通知消息警报。

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.

第二个问题是否有可能第一轮立即调用 Ajax 调用,然后每 5 分钟调用所有其他调用?因为我希望系统在他们登录系统后立即检查,然后每 5 分钟检查一次。

Here is my code

这是我的代码

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

    return false;
}

setInterval("getAjaxNotice()", 50000);

回答by Scott Montgomerie

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

首先,您应该将初始化代码包装在一个 onLoad 函数中:

$(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:

让它出现一次很容易,使用 .html() 代替设置内容而不是添加内容:

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

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

第三,作为样式说明,您不应将字符串传递给 setInterval()。相反,传递一个函数名称:

setInterval( getAjaxNotice, 50000 );

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

最后,要让它现在和每 5 分钟后再次调用该函数,请使用:

// 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.

另请注意,50000 是 50 秒,而不是 5 分钟。5 分钟将是 5 * 60 * 1000 = 300000。

回答by Patrick

A couple of things...

有几件事...

setInterval("getAjaxNotice()", 50000);

Is not 5 minutes.

不是5分钟。

5 minutes = 300000 milliseconds.

5 分钟 = 300000 毫秒。

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

如果你想让它立即运行,然后每 5 分钟执行一次,你可以简单地做

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



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

       setInterval( getAjaxNotice(), 300000 );

});

回答by dlev

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

对于第一个问题,您应该存储来自 的返回值setInterval,然后clearInterval(myIntervalId)在收到警报时调用。

For the second problem, you can call getAjaxNoticeonce during onload of the body, and then if no alerts are received, call setIntervalat that point.

对于第二个问题,你可以getAjaxNotice在加载body的时候调用一次,然后如果没有收到警报,就setInterval在那个时候调用。

回答by Rocket Hazmat

setInterval's time is in milliseconds.

setInterval的时间以毫秒为单位。

5 minutes * 60 seconds * 1000 milliseconds = 300000ms

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

另外,我建议您将函数传递给而setInterval不是字符串,这样您就可以避免隐式使用eval.

setInterval(getAjaxNotice, 300000);

To call getAjaxNoticeat the start of the page, put it in a readyblock.

getAjaxNotice在页面的开头调用,请将其放入ready块中。

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

回答by Mark At Ramp51

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:

在您的情况下,听起来您正在处理一些问题。因此,使用您当前的方法,您可以最初进行 ajax 调用并在设置超时后跟进:

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)

其次,如果您有某种类型的“消息确认”事件,则可以轻松确保用户只收到一次消息。假设您的用户可以在多台计算机上打开浏览器,如果您让用户单击消息或单击确定按钮,或执行某些操作以确认他们收到消息,您可以触发另一个 ajax 调用以从缓冲区中删除该消息在您的服务器上,但仍会在所有打开的浏览器上显示它。本地浏览器只会显示一次,因为如果消息重复,您可以阻止在客户端显示它(基于对您的应用程序有意义的标准)

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.

但是,您应该研究长轮询和 COMET,http://en.wikipedia.org/wiki/Comet_(programming)。Comet 是一个基于服务器端事件向 Web 浏览器推送通知的概念,而不是 Web 浏览器不断向服务器请求更改。

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.

由于 Web 框架和浏览器的限制,这是通过一些技术实现的,但长轮询似乎是最普遍的。HTML5 和 websockets 正在尝试进行一些更改,以防止一起进行轮询,但尚不可用。

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.

长轮询、http://en.wikipedia.org/wiki/Push_technology和基于 COMET 的架构已被 meebo 和 facebook 等公司使用。不要引用我的话,但出于某种原因,我倾向于相信 facebook 使用基于 Erlang 的网络服务器来提供他们的聊天消息。Erlang 和 NodeJs 只是一些解决方案,您可以使用它们来构建轻量级 Web 服务器,这些服务器可以很好地处理大量长轮询请求访问您的服务器。

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.

您绝对应该自己阅读所有这些内容,因为有大量可用信息。我已经尝试在 Amazon EC2 上创建 NodeJs 服务器,因为我传统上从事 .NET 工作,并且不认为 IIS 是支持使用长轮询的 .net 应用程序的长轮询功能的正确解决方案,我不得不说我非常喜欢 NodeJs。此外,与我对 Erlang 的有限了解相比,JavaScript 语言对我来说更为熟悉。