i have a JavaScript/jQuery code function that is supposed to call itself up to ten times if there is no data available (determined by web service call). I have implemented the code but the logging inside the web service call indicates that it is called only 1 or 2 times. What is the error in this code?
function CallIsDataReady(input) {
var timer;
var count = 0;
$.ajax({
url: "https://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
success: function (data) {
if (!data) {
setTimeout(function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}, 1000);
} else {
console.log("data returned - returning true");
//Continue as data is ready
var tableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
GetDataFromServer(0, tableView.get_pageSize());
}
},
error: function (jqXHR, textStatus, errThrown) {
console.log("AJAX call failed in CallIsDataReady");
console.log(errThrown);
}
});
}
EDIT: It should try up to ten times and then quit, not go on to the GetDataFromServer. It should return an error. How can I do that?
setTimeout is meant to trigger a function call once, and only once.
Repeat call to setTimeout from within your timeouted callback if you want this to work:
function CallIsDataReady(input) {
var timer;
var count = 0;
function callWebService(){
console.log('calling webservice');
$.ajax({
url: "https://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
success: function (data) {
console.log('count = ' + count);
console.log('data = ' + data);
if (!data){
if(count < 10) {
count++;
setTimeout(callWebService, 1000);
} else {
count = 0;
}
}else{
console.log("data returned - returning true");
//Continue as data is ready
var tableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
GetDataFromServer(0, tableView.get_pageSize());
}
},
error: function (jqXHR, textStatus, errThrown) {
console.log("AJAX call failed in CallIsDataReady");
console.log(errThrown);
}
});
};
callWebService();
}
count is being reset every time CallIsDataReady is called.
Replace:
function CallIsDataReady(input) {
var timer;
var count = 0;
With:
var count = 0;
function CallIsDataReady(input) { // You won't need the `timer` variable
This will set count to 0 before the first call of CallIsDataReady. Then, each call, the count will be incremented.
Now, to handle that counter properly, replace:
if (!data) {
setTimeout(function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}, 1000);
With:
if (!data && count !== 10) {
setTimeout(function(input) {
CallIsDataReady(input);
count++;
}, 1000);
Now, I'm not sure what inputInner is supposed to be, so I replaced that with input. If you want a different variable to be passed to subsequent calls, you'll have to assign a value to inputInner.
In addition to making timer and count into global variables, I think you need to assign a value to inputInner when you execute it:
if (!data) {
setTimeout(function() {
function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}(input);
}, 1000);
}
It looks like you are trying to use setTimeout instead of setInterval. setTimeout calls function only once after certain amount of time. setInterval will be calling your function in intervals until you call clearInterval.
http://www.w3schools.com/jsref/met_win_setinterval.asp
timer= setInterval(function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}, 1000);
Related
i have a script that reload the page when the value is >= 100 the problem is that location.reload(true); are not working in ie11, i also have tried with window.location = self.location.href; but i am having the same problem, in other browsers it works good.
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
}, 2000);
}
});
You don't appear to have defined self anywhere, so you may have an error there. Beyond that, you're trying to assign the value of href as the whole value of location - which is meant to be an object. Instead, try:
window.location.href = window.location.href;
Try to move the if statement into the success callback.
Like that you can clear the interval into the same stack and reload the page on the good
.
$(function() {
if (value < 100) {
var timer = setInterval(function() {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function(msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
},
error: function(err) {
clearInterval(timer);
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
place the if in the success function, ajax is asynchronous the if will execute immediately but value will change after the ajax has completed so the code may never reach the if statement
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value) {
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
location.reload(true);
}
}
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
I am trying to stop my Timeout when I received data back from my ajax post. However, I get the data back, it updates my html, but the timer is still going. What's going wrong?
function getResponse() {
var i = 0;
var reply = null;
var myTimer;
while (i < 24 && reply == null) {
(function(i) {
myTimer = setTimeout(function() {
$.ajax({
url: '/getResponse',
data: "123456",
type: 'POST',
success: function (data) {
console.log("HERE data2 " + data);
if(data != "" || data != null){
reply = data;
document.getElementById("responseText").innerHTML = reply;
clearTimeout(myTimer);
}
},
error: function (error) {
document.getElementById("responseText").innerHTML = error;
console.log(error);
}
});
}, 5000 * i)
})(i++)
}
Here you are overwriting your global myTimer variable in each iteration of the while loop. So every time you are doing clearTimeout(myTimer) you are just clearing the timeout of the last setTimeout that is run when i becomes 23 and not for setTimeout created in the previous 22 iterations of the while loop. You actually have to declare the myTimer variable inside the IIFE in the while loop like the following to clearTimeout for all the 23 setTimeouts created during the while loop:
function getResponse() {
var i = 0;
var reply = null;
// var myTimer;
while (i < 24 && reply == null) {
(function(i) {
var myTimer = setTimeout(function() { // Declare myTimer here
$.ajax({
url: '/getResponse',
data: "123456",
type: 'POST',
success: function (data) {
console.log("HERE data2 " + data);
if(data != "" || data != null){
reply = data;
document.getElementById("responseText").innerHTML = reply;
clearTimeout(myTimer);
}
},
error: function (error) {
document.getElementById("responseText").innerHTML = error;
console.log(error);
}
});
}, 5000 * i)
})(i++)
}
It is cleared. But you are calling your function over and over (23 times) and every time you are setting new timeout and clearing him again.
Why the timeout don't work?
If i work without the function sleep, they return to me an undefined data..
With this function they work but without sleeping time, they go directly to the last image.. :-/
function sleep(value, data, i) {
document.getElementById(value).src = data[i];
}
function imgAnimation(value){
var img = document.getElementById(value).src;
$.ajax({
type: "POST",
url: "static/cercaThumbs.php",
data: 'id=' + value,
datatype: 'json',
success: function (data) {
var elements = Object.keys(data).length;
for (var i = 0; i < elements; i++) {
if(i == elements){i = 0;}
setTimeout(sleep(value, data, i), 300);
}
}
});
}
You need to pass a function to setTimeout. You're calling the function sleep and passing its result.
setTimeout(function() {
sleep(value, data, i);
}, 300);
But it still won't work, because you're setting a bunch of timeouts at the same time, so they'll all trigger 300ms later at the same time. To animate you might try something like:
var data = [
'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0030.png',
'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0031.png',
'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0032.png',
]
var frame = 0;
var elements = data.length;
var animation = setInterval(function() {
frame = (frame + 1) % elements;
document.getElementById('test').src = data[frame];
}, 300);
<img id=test>
This sets up a single repeating callback which can advance to the next frame each time. In the example above it will loop forever, or you can call clearInterval(animation) once you're finished.
Ok, with the help of Nick, this is the correct code:
function imgAnimation(value){
$.ajax({
type: "POST",
url: "static/cercaThumbs.php",
data: 'id=' + value,
datatype: 'json',
success: function (data) {
var elements = Object.keys(data).length;
var frame = 0;
var animation = setInterval(function() {
frame = (frame + 1) % elements;
document.getElementById(value).src = data[frame];
}, 500);
document.getElementById(value).addEventListener("mouseout", function(){
clearInterval(animation);
document.getElementById(value).src = data['0'];
});
}
});
}
I have the following part of a jQuery .ajax call. It checks every second I believe. How can I get to stop after 10 tries?
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
EDIT: I implemented one solution but the logging for the service call seems to stop after 2 times.
function CallIsDataReady(input) {
var timer;
var count = 0;
$.ajax({
url: "http://www.example.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
// dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}, 1000);
}
else {
console.log("data returned - calling callUpDateGrid");
//Continue as data is ready
callUpdateGrid(input);
}
},
error: function (jqXHR, textStatus, errThrown) {
console.log("AJAX call failed in CallIsDataReady");
console.log(errThrown);
}
});
Just assign your setTimeout to a variable, and use a counter, when it reaches 10, call clearTimeout()
user setInterval with a counter:
if (!data) {
var count = 0;
var interval;
interval = setInterval(function (inputInner) {
if (count === 10) {
clearInterval(interval);
return;
}
CallIsDataReady(inputInner);
count++;
}, 1000);
}
// global variable - should be outside your ajax function
var timer;
var count = 0;
....
success : function( data) {
if( ! data ) {
// don't know where you are getting inputInner. assuming its a global variable
timer = setInterval ( function ( inputInner ) {
CallIsDataReady(inputInner);
count++;
if ( count == 10 ) {
clearInterval(timer);
count = 0;
}
}, 1000);
}
}
Use an interval
var count = 0,
handler = setInterval(dostuff, 1000);
function dostuff(inputInner){
//CallIsDataReady(inputInner);
if(++count === 10)
clearInterval(handler);
}
http://jsfiddle.net/mGgLz/
However, you should never rely on the assumption that the ajax call always takes < 1000ms. Check the readyState on the XHR and make sure it's 4 before polling again.
The below code is a timer for my site's ads. The way its setup now it waits for the page to load fully before starting the timer. What I would like to do is to Alter this slightly to only wait 5 seconds, if the page has not finished loading by then just go ahead and start the timer. I have no idea how to do this at all.
$(document).ready(function () {
ptcevolution_surfer();
});
function showadbar(error) {
$("#pgl").removeAttr("onload");
if (error == '') {
$(".adwait").fadeOut(1000, function () {
$("#surfbar").html('<div class="progressbar" id="progress"><div id="progressbar"></div></div>');
$("#progressbar").link2progress(secs, function () {
endprogress('');
});
});
} else {
$(".adwait").fadeOut(1000, function () {
$("#surfbar").html("<div class='errorbox'>" + error + "</div>");
$(".errorbox").fadeIn(1000);
});
}
}
/* End Surf Bar */
function endprogress(masterkey) {
if (masterkey == '') {
$("#surfbar").fadeOut('slow', function () {
$("#vnumbers").fadeIn('slow');
});
return false;
} else {
$("#vnumbers").fadeOut('slow', function () {
$(this).remove();
$("#surfbar").fadeIn('slow');
});
}
$("#surfbar").html("Please wait...");
var dataString = 'action=validate&t=' + adtk + '&masterkey=' + masterkey;
$.ajax({
type: "POST",
url: "index.php?view=surfer&",
data: dataString,
success: function (msg) {
if (msg == 'ok') {
$("#surfbar").html("<div class='successbox'>" + adcredited + "</div>");
$(".successbox").fadeIn('slow');
if (adtk == 'YWRtaW5hZHZlcnRpc2VtZW50') {
window.opener.hideAdminAdvertisement();
} else {
window.opener.hideAdvertisement(adtk);
}
return false;
} else {
$("#surfbar").html("<div class='errorbox'>" + msg + "</div>");
$(".errorbox").fadeIn('slow');
}
}
});
}
function ptcevolution_surfer() {
if (top != self) {
try {
top.location = self.location;
} catch (err) {
self.location = '/FrameDenied.aspx';
}
}
$("#surfbar").html("<div class='adwait'>" + adwait + "</div>");
}
By your use of $, I'm going to assume jQuery
var __init = (function () {
var initialised = 0; // set a flag, I've hidden this inside scope
return function () { // initialisation function
if (initialised) return; // do nothing if initialised
initialised = 1; // set initialised flag
ptcevolution_surfer(); // do whatever
};
}()); // self-invocation generates the function with scoped var
window.setTimeout(__init, 5e3); // 5 seconds
$(__init); // on page ready
Now what happens? The first time the function is fired, it prevents itself from being fired a second time, then starts off whatever you want done.