How to change frequency of PeriodicalExecuter based on server response? - javascript

I have a reload function that reloads a page periodically. However, I would like to reload the page only if certain conditions are met (if not, increase the interval for the reload). So I tried using PeriodicalExecutor and an Ajax call like this -
<script type="text/javascript">
var nextReload = 10;
function reloadPage() {
document.location.reload();
return new PeriodicalExecuter(function(pe) {
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
var response = ...
nextReload = response.nextReload;
},
onFailure: function(){ ... }
});
this.frequency = nextReload; // doesn't do what I'd like it to do.
}, nextReload);
}
var myReload = reloadPage();
</script>
As you can see, the Ajax call returns the time (in seconds) in which the next reload should occur. However, I am not able to set the frequency of the PeriodicalExecutor to nextReload.
So how can I reload the page at variable time intervals?

Would something like this work for you?
<script>
function tryReload(){
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
if(transport == seconds){
// call self in x seconds
setTimeout(tryReload, (1000*transport));
}
else{ // transport is a URL
window.location = transport;
}
},
onFailure: function(){ ... }
});
}
//start it up!
tryReload();
</script>

Based on #Rocket Hazmat's suggestion, this worked for me -
function reloadPage() {
document.location.reload();
return new PeriodicalExecuter(function(pe) {
var that = this;
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
var response = ...
nextReload = response.nextReload;
that.frequency = next;
that.stop();
that.registerCallback();
},
onFailure: function(){ ... }
});
}, nextReload);
}

Related

Firing a function every x seconds

I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds

how to recall function from controller using javascript

setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
var url = '/Lines/dbcheck/?LineID=#ViewBag.LineID&ProductID=#ViewBag.ProductID&LastID=#LastID';
var data = {};
$.get(url, data, function(response_text){
if (response_text == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
}, "text");
}
I already can call function from controller but only 1 time. I would like to create function to check the data from database and return 1 or 0. If it is 0 i would like to make a delay for 5 sec and then recall function again.
the problem is the parameter response_text is not updated because I can call the function from controller only first time
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
$.ajax({
cache : false,
dataType: "json",
type: "GET",
async:false,
url: url ,
success: function (fdata) {
if (fdata == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
},
error: function (reponse) {
}
});
}
Your code executed immediately because of you passing () it is not wait for the time delay.
setInterval(makeAjaxCall(), 5000);
change to
setInterval(makeAjaxCall, 5000);
or alternate way
setInterval(function() {
makeAjaxCall();
}, 5000);

simple ajax request with interval

I recently began learning Ajax and jQuery. So yesterday I started to programm a simple ajax request for a formular, that sends a select list value to a php script and reads something out of a database.
It works so far!
But the problem is, that when I click on the send button, it starts the request, 1 second later. I know that it has something to do with my interval. When I click on the send button, I start the request and every second it requests it also, so that I have the opportunity, to auto-refresh new income entries.
But I'd like to have that interval cycle every second, but the first time I press the button it should load immediately, not just 1 second later.
Here is my code:
http://jsbin.com/qitojawuva/1/edit
$(document).ready(function () {
var interval = 0;
$("#form1").submit(function () {
if (interval === 0) {
interval = setInterval(function () {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}, 1000);
}
return false;
});
});
Thanks!
I might be something like the following you're looking for.
$(document).ready(function () {
var isFirstTime = true;
function sendForm() {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}
$("#form1").submit(function () {
if (isFirstTime) {
sendForm();
isFirstTime = false;
} else {
setTimeout(function () {
sendForm();
}, 1000);
}
return false;
});
});
So, use setTimeout when the callback has finished as setInterval just keeps running whether or not your callback has finished.
$(function () {
$("#form1").submit(postData);
function postData() {
var url = "tbladen.php",
data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
setTimeout(postData, 1000);
}
});
return false;
}
});
Kind of related demo

Javascript setInterval within setInterval timer increasing

I have an ajax request that refreshes a page using setInterval every 5 seconds.
Within that ajax request I have another setInterval function to blink a every half second if a condition is true.
What happens is it seems to work fine after the initial ajax call. However, with every 5 second refresh ajax refresh, my blink function timer is halved, effectively doubling the speed.
Any help would be appreciated, thanks!
Here is the code:
$(document).ready(function() {
var refreshRate = 5000;
var autoRefresh = setInterval(
function () // Call out to get the time
{
$.ajax({
type: 'GET',
success: function(data){
document.getElementById('data').innerHTML=data;
var blink = setInterval (function () {
var blink_cell = $("#blink_div").html();
if (blink_cell > 0) {
$("#blink_div").toggleClass("blink");
} else {
$("#blink_div").addClass("invisible");
}
},500);
} // end success
}); // end ajax call
}, refreshRate);// end check
}); // end ready
Be concerned with the scope of your variables and clear the blink intervall before initiating a new one.
$(document).ready(function() {
var refreshRate = 5000;
var blink = -1;
var autoRefresh = setInterval(
function () // Call out to get the time
{
$.ajax({
type: 'GET',
success: function(data){
document.getElementById('data').innerHTML=data;
if(blink>-1) clearInterval(blink);
blink = setInterval (function () {
var blink_cell = $("#blink_div").html();
if (blink_cell > 0) {
$("#blink_div").toggleClass("blink");
} else {
$("#blink_div").addClass("invisible");
}
},500);
} // end success
}); // end ajax call
}, refreshRate);// end check
}); // end ready
$(document).ready(function () {
var _url = ''; // Put your URL here.
var _checkServerTime = 5000;
var _blinkTime = 500;
function _blink() {
// Do something here.
var condition = true; // Put condition here.
if (condition) setTimeout(_blink, _blinkTime);
}
function _handleData(data) {
$('#data').html(data);
_blink();
}
function _checkServer() {
$.get(_url, _handleData);
}
setInterval(_checkServer, _checkServerTime);
});

how to check if there is "no route to host" over and over during streaming a video?

I know that I should use setInterval(function(), time_interval_ms), but I don't know how to write the function() to check if there is a route to host!
You can create a function that pings your host using AJAX. If the AJAX call was successful, your host is available; if not, your host is unavailable. You then use setInterval to call this "ping" method.
Here is an example of this:
var timerDuration = 1000;
var hostUrl = "/your_url_to_ping.php";
var isAvailable = false;
$(document).ready(function() {
var timer = setInterval(function() {
pingServer();
}, timerDuration);
});
function updateStatus() {
var o = $('#df');
o.text('Is Available: ' + isAvailable);
}
function pingServer() {
isAvailable = false;
$.ajax({
url: hostUrl,
success: function(data) {
isAvailable = true;
},
error: function() {
isAvailable = false;
},
complete: function() {
updateStatus();
}
});
}
the fiddle
And here are guides you might require:
jQuery: http://jquery.com/
Cross-domain AJAX: http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide

Categories