cat
cat

Reputation: 749

How can I extend interval time every time it runs?

In my application, every 10 seconds, it calls this ajax to reload the number of received mails.
However, it seems that my PC is getting so heated as time goes by, even when I'm doing nothing but just staying at the same page in my application.

I'd like to add extensional 10 more seconds every time it runs.
Then it resets to 0, when the whole page is loaded again.
Is it possible?

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

Upvotes: 0

Views: 122

Answers (2)

Novae
Novae

Reputation: 1171

You can easily be done moving the setTimeout out of the erb file and to the complete function on the AJAX call. The result would look something like this:

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

Upvotes: 0

jvnill
jvnill

Reputation: 29599

you can define a global javascript variable on the view. window.timerCounter = 0 then increment this variable on refresh_mail.js.erb

window.timerCounter += 1
setTimeout(refreshMail, 10000 + (window.timerCounter * 10000));

Upvotes: 2

Related Questions