I'm having problems with a function firing multiple times on click. Specifically, in the below code, the userloggedin(); function fires multiple times when clicked. Typically, it fires once the first time, 3 times the next time and 6 the next.
var timer = null;
function sessCountdown() {
var sec = 120;
timer = setInterval(function() {
sec--;
if (sec >= 0) {
span = document.getElementById("count");
span.innerHTML = sec;
}
}, 1000);
}
function getUserInfo() {
var getUserInfo = $.ajax({
type: 'Get',
url: Config.engineUrl + '?AUserSessionInfo',
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
});
getUserInfo.done(function(data, jqXHR) {
var sessionModal = $('#session-modal');
if (data.TimeLeft > 0 && data.TimeLeft <= 2 && !sessionModal.hasClass('in')) {
sessionModal.modal('show');
sessCountdown();
} else if (data.TimeLeft === 0){
$('.logout').trigger('click');
}
sessionModal.on('shown.bs.modal', function(e) {
$('#btnSession').on('click', function() {
clearInterval(timer);
userLoggedin();
});
});
});
}
//Check for session info every 60 seconds
setInterval(getUserInfo, 60000);
I appreciate any tips for resolving this that you can provide. Thanks.
Updated Code - With Resolution
var timer = null;
function sessCountdown() {
var sec = 120;
timer = setInterval(function() {
sec--;
if (sec >= 0) {
span = document.getElementById("count");
span.innerHTML = sec;
}
}, 1000);
}
function getUserInfo() {
var sessionModal = $('#session-modal'),
getUserInfo = $.ajax({
type: 'Get',
url: Config.engineUrl + '?AUserSessionInfo',
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
});
getUserInfo.done(function(data, jqXHR) {
if (data.TimeLeft > 0 && data.TimeLeft <= 2 && !sessionModal.hasClass('in')) {
sessionModal.modal('show');
sessCountdown();
} else if (data.TimeLeft === 0) {
$('.logout').trigger('click');
}
});
}
$('#btnSession').on('click', function() {
clearInterval(timer);
userLoggedin();
});
//Check for session info every 60 seconds
setInterval(getUserInfo, 60000);
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);
}
});
For the following code, the emailCnt is 50 for first iteration, I need 25 in next iteration. What is the possible way to access the variable value outside the ajax success and break the for loop execution?
var limit = 50;
var emailCnt = limit;
for (var i = 0; i < 20; i++) {
console.log(emailCnt);///this value is 50 instead I need 25
if (emailCnt < limit && i != 0) {
break;
}
setTimeout(function () {
submit_post(slNo, limit, function (output) {
slNo = output;
emailCnt = 25;
$('#load_data').html('Hello');
});
}, 1000);
}
function submit_post(slNo, limit, handleData) {
$.ajax({
type: 'POST',
async: false,
url: url,
data: { slNo: slNo, limit: limit },
success: function (data) { handleData(data); }
});
}
This successfully worked for me
var limit = 50;
var emailCnt = limit;
function submit_post(slNo, limit)
{
var result="";
$.ajax({
type: 'POST',
async: false,
url: url,
data: {slNo:slNo, limit:limit},
success: function(data) { result = data; }
});
return result;
}
for(var i=0;i<20;i++)
{
if(emailCnt < limit && i != 0)
{
break;
}
setTimeout(function () {
var output = submit_post(slNo, limit);
slNo = output;
emailCnt = 25;
$('#load_data').html('Hello');
}, 1000);
}
I plan to use Ghost.py to scrape a web page which is updated every 5 seconds by setInterval.
How can I scrape the updated data by Ghost.py repeatedly, once there is a new update by this script?
The setInterval code below:
(function () {
var template;
(function () {
template = $("#template1 tbody").html();
GetData();
})();
function GetData() {
var max = 100,
sn = $.data(document, "sn");
if (sn === undefined) {
sn = 0;
} else {
sn = parseInt(sn, 10);
}
$.ajax({
url: path + "ashx/notice.ashx",
async: true,
cache: false,
data: {
act: "GetBotSignal",
sn: sn,
max: max
},
type: "get",
dataType: "json",
success: function (data) {
if (data !== null && data.length !== 0) {
var html = "";
var expselbox = $(".exp-sel-box");
for (var i = 0, j = data.length; i < j; i++) {
var item = template;
item = item.replace(/\{0}/g, data[i].SignalOccurTime);
(parseFloat(data[i].Ratio) >= 2 && parseFloat(data[i].Probability) >= 50) ? " sp" : "");
html += item;
}
expselbox.prepend("<tr ef=\"1\" style=\"height:0px;\"></tr>");
expselbox.find("tr[ef=1]").animate({ "height": (34 * data.length) + "px" }, "fast", function () {
expselbox.find("tr[ef='1']").remove();
expselbox.prepend(html);
expselbox.find("tr:hidden").fadeIn("fast");
expselbox.find("tr:gt(" + max + ")").remove();
$.data(document, "sn", data[0].SN);
ScrollBar($(".expscall-out"), 642, 342, true);
});
}
}
});
}
if (srvTime.getHours() > 7 && srvTime.getHours() < 14) {
setInterval(function () {
GetData();
}, 5000);
}
})();
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.
I need to call a function every 5 minutes for an 8 hour period. The catch is it must be the on the same day. For example if the user logs onto the system at 11:59pm on 3/29 and it's now 12:01am on 3/30 the function should no longer be called.
I know how to call it ever 5 minutes and have the jQuery ajax call coded; that part is fine. My problem is figuring out the date.
Here is the code:
var startDay;
function keepAlive(currDay) {
var today = new Date().getDate();
if (currDay == today) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ alive: 'true' }",
url: "../ses/imsi_ses_edit.aspx/KeepSessionAlive",
dataType: "json",
success: function(data) {
},
error: function(response) {
alert(response.responseText);
}
});
}
}
window.onload = function() {
startDay = new Date().getDate();
keepAlive(startDay); //Make sure the function fires as soon as the page is loaded
setTimeout(keepAlive, 300000); //Then set it to run again after five minutes
}
var initDate = new Date(); // Or get the user login date from an HTML element (i.e. hidden input)
var interval;
function keepAlive() {
// Do stuff (ajax call)
}
window.onload = function() {
keepAlive();
interval = window.setInterval(function() {
var now = new Date();
if(now.getTime() - initDate.getTime() < 8*60*60*1000 && now.getDate() == initDate.getDate()) {
keepAlive();
}
else {
// Stop the interval
window.clearInterval(interval);
}
}, 5*60*1000);
}
function keepAlive(currDay) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ alive: 'true' }",
url: "../ses/imsi_ses_edit.aspx/KeepSessionAlive",
dataType: "json",
success: function(data) {
},
error: function(response) {
alert(response.responseText);
}
});
}
window.onload = function() {
var startDay = new Date().getDate();
var startTime = new Date().getTime();
var interval;
keepAlive(startDay); //Make sure the function fires as soon as the page is loaded
interval = setInterval( function () {
if (startDay != new Date().getDate() || startTime < (new Date().getTime() - 1000*60*60*8)) {
clearInterval(interval);
return;
}
keepAlive();
}, 300000); //Then set it to run again after five minutes
}