如何在每次运行时延长间隔时间?

时间:2013-02-06 12:36:30

标签: ruby-on-rails ajax ruby-on-rails-3 jquery

在我的应用程序中,每隔10秒钟,它会调用此ajax来重新加载收到的邮件数量 然而,随着时间的推移,我的电脑似乎变得如此激烈,即使我只是在我的应用程序中停留在同一页面上。

每次运行时,我想再延长10秒 然后当重新加载整个页面时,它重置为0 有可能吗?

refresh_mail_count.js

jQuery(document).ready(function () {
    refreshMail();
});


function refreshMail() {
  $.ajax({
    url: "/messages/refresh_mail",
    type: "GET",
    dataType: "script",
  });
}

refresh_mail.js.erb

$('#message_count').html("<%= j(render(:partial => 'layouts/message_received_count', :object => @message_count)) %>");
setTimeout(refreshMail,10000);

2 个答案:

答案 0 :(得分:2)

您可以在视图上定义全局javascript变量。 window.timerCounter = 0然后在refresh_mail.js.erb

上增加此变量
window.timerCounter += 1
setTimeout(refreshMail, 10000 + (window.timerCounter * 10000));

答案 1 :(得分:0)

您可以轻松地将setTimeout移出erb文件并移动到AJAX调用的完整函数。结果看起来像这样:

var emailPollDelay, initialEmailPollDelay = 10000, 10000; jQuery(document).ready(function () { refreshMail(); });

function refreshMail() { $.ajax({ url: "/messages/refresh_mail", type: "GET", dataType: "script", complete: function() { setTimeout(refreshmail, (initialEmailPollDelay += emailPollDelay); } }); }