jquery / javascript setInterval [英] jquery/javascript setInterval

查看:85
本文介绍了jquery / javascript setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

第二个问题是第一轮可能会立即调用Ajax,然后每5分钟调用一次所有其他调用吗?因为我希望系统在他们登录系统后立即检查n然后每隔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.

这是我的代码

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

    return false;
}

setInterval("getAjaxNotice()", 50000);


推荐答案

首先,你应该把初始化代码包装好onLoad函数:

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

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

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

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

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

第三,作为样式注释,不应将字符串传递给setInterval()。相反,传递函数名称:

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

setInterval( getAjaxNotice, 50000 );

最后,为了让它现在调用该函数,并且每隔5分钟再调用一次,使用:

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();

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

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

这篇关于jquery / javascript setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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