Javascript Application is crashing every 4-5 hrs in chrome and firefox - angularjs

My application is crashing every 4-5 hrs and I am not sure it is happening because of memory leak or any code performance issue.
I have 3-4 functions which have timeouts to call self every 5 sec and they does some data massaging before painting the DOM.
As you can see my snapshots keep on increasing every time I take new snapshot.
Unable to find what exactly is happening. But if we look at the snapshots we can say that the strings has been increasing significantly from snapshot 1 to snapshot 9.
Any help is appreciated.
Sample code:
function fetchSummary() {
if(!$rootScope.pageVisible) {
$scope.fetchSummaryTimeout = $timeout(fetchSummary, 1000);
$scope.lastRefreshedDateTime = new Date();
return;
}
$http
.get(apiUri + '/statusboard/api/summaryDb')
.success(function (response) {
if (response && response.length) {
$scope.databases = response[0];
$scope.fetchSummaryTimeout = $timeout(fetchSummary, 5000);
var i, j, l;
//alert counts
angular.forEach($scope.databases.summary, function (summary) {
if (summary.eventType === "database_connection_alert") {
$scope.connectionCount += summary.count;
}
if (summary.eventType === "database_session_alert" || summary.eventType === "database_load_alert") {
$scope.warnCount += summary.count;
}
});
for (l = 0; l < $scope.databases.components.length; l++) {
var component = $scope.databases.components[l];
//some data stuff
for (j = 0; j < component.summary.length; j++) {
var summary = component.summary[j];
}}
$scope.coloCounts.any = $scope.coloCounts.All + $scope.coloCounts.lvs + $scope.coloCounts.slc + $scope.coloCounts.phx;
for (i = 0; i < $scope.databases.vcsStatus.length; i++) {
//Some stuff
}
}
} else {
$scope.fetchSummaryTimeout = $timeout(fetchSummary, 5000);
}
angular.element("#last-updated, #last-updated-overlay").remove();
})
.error(function () {
$scope.fetchSummaryTimeout = $timeout(fetchSummary, 5000);
});
}
}
"$scope.databases" is the variable every time i set the response to.

Related

Execute methods sequence - React

I have written following code to get current user group Ids and later from that Ids I wanted to filter data from SharePoint list. First I want to execute
ServiceManager.getRemoteService().getCurrentUserGroups()
method. Once I get group Ids, I want to execute the next method. But unfortunately filter part of the REST query is blank because
this.groupIdString
is blank. This may be because both methods are executed same time. I'm new to React and I want to know is there any best approach to manage this scenario. Basically I want to execute the methods in the order I write.
public componentDidMount() {
this.groupIdString= "";
ServiceManager.getRemoteService().getCurrentUserGroups(this.props.siteUrl, "/_api/web/currentuser/groups").then((value) => {
if (value[0]) {
for (let i: number = 0; i < value.length; i++) {
if(value[i].Id != undefined){
this.groupIdString += "(UserGroupsId eq " + value[i].Id.toString()+")";
}
}
}
});
const restQuery = "/_api/Web/Lists/GetByTitle('Weather')/Items?$select=Title,NewsBody,UserGroupsId&$filter=("+this.groupIdString+")";
ServiceManager.getRemoteService().getWeatherListItems(this.props.siteUrl, restQuery).then((value) => {
if (value[0]) {
//code
}
});
}
#Sivakumar Piratheeban,
You can put the second request in the callback of the first call.
public componentDidMount() {
this.groupIdString = "";
ServiceManager.getRemoteService().getCurrentUserGroups(this.props.siteUrl, "/_api/web/currentuser/groups").then((value) => {
if (value[0]) {
for (let i: number = 0; i < value.length; i++) {
if (value[i].Id != undefined) {
this.groupIdString += "(UserGroupsId eq " + value[i].Id.toString() + ")";
}
}
// Second
const restQuery = "/_api/Web/Lists/GetByTitle('Weather')/Items?$select=Title,NewsBody,UserGroupsId&$filter=(" + this.groupIdString + ")";
ServiceManager.getRemoteService().getWeatherListItems(this.props.siteUrl, restQuery).then((value) => {
if (value[0]) {
//code
}
});
//
}
});
}
BR

AngularJS - Delete check box is not working correctly and only deleting one at a time

I've written out a block of code that allows the user to check or uncheck entities that will be added or removed via web services. My add function seems to be working correctly and provides the ability to add multiple entities. However, my delete function isn't working the same. It doesn't delete each time, and can only delete one at a time. I'm struggling since the code is effectively the same as the add, so I don't know if the issue is AngularJS related or perhaps my web service isn't working correctly.
Edit: I've actually noticed that the for loop goes through it all but doesn't select the correct id, it always starts from the first one.
var toDeleteService = [];
for (var i = 0; i < $scope.siteServices.length; i++) {
if ($scope.siteServices[i].chosen != $scope.siteServices[i].origChosen) {
if ($scope.siteServices[i].chosen == true) {
toAddService.push(i);
}
else {
toDeleteService.push(i);
}
}
}
if (toDeleteService.length > 0) {
var deleteRequest = {};
deleteRequest.services = [];
for (var i = 0; i < toDeleteService.length; i++) {
var parentServiceName = $scope.siteServices[i].parentServiceName;
var j = 0;
for (; j < deleteRequest.services.length; j++) {
if (deleteRequest.services[j].parentServiceName == parentServiceName) {
break;
}
}
if (j == deleteRequest.services.length) {
deleteRequest.services[j] = {};
deleteRequest.services[j].parentServiceName = parentServiceName;
deleteRequest.services[j].subservices = [];
}
var service = {};
service.serviceId = $scope.siteServices[i].serviceId;
deleteRequest.services[j].subservices.push(service);
}
var deleteUrl = "api/sites/" + $scope.targetEntity.siteId + "/services/" + service.serviceId;
$http.delete(deleteUrl)
.then(function (response) {
});
}
As I understood it you are trying to remove siteServices based by numbers stored in var toDeleteServices = [] so you need to access those numbers by its index. but in service.serviceId = $scope.siteServices[i].serviceId; you are using i instead.
service.serviceId = $scope.siteServices[toDeleteServices[i]].serviceId; as you need actual number of the service to delete.
If I understood your code correctly.

Loading of paginated data from API

I am working on a system that currently requires me to load all items from an API.
The API is built with pagination feature in it. I keep calling the API a number of times and $http.get cursing the system not to respond. For example, once I load the page that needs to call the API many times (like 50 to 80 times depending on the number of pages), for a few minutes anything I do won't respond until the calling of the API is almost finished. I already tried a lot of ways but it won't work.
$scope.loadAllPagedItems = function (category_uuid, max_pageitem, item_perpage) {
for (var a = 0 ; a < max_pageitem; a++) {
itemResource.findItems(category_uuid, item_perpage, a).then(function (response) {
if (response.data.data.length > 0) {
for (var a = 2 ; a < $scope.categories.length; a++) {
if ($scope.categories[a][0].category_uuid == response.data.data[0].category_uuid) {
for (var j = 0; j < response.data.data.length; j++) {
$scope.categories[a][0].data.push(response.data.data[j]);
}
}
}
}
}, function (error) {
console.log(error);
})
}
}
Is there any way I can do this better?
Sequentially Retrieving Paginated Data from an Asynchronous API
$scope.loadAllPagedItems = function(category_uuid, max_pageitem, item_perpage) {
var promise = $q.when([]);
for (let a = 0 ; a < max_pageitem; a++) {
promise = promise
.then(function(dataArray) {
var p = itemResource.findItems(category_uuid, item_perpage, a);
p = p.then(function (response) {
return dataArray.concat(response.data.data);
});
return p;
});
};
return promise;
};
The above example, executes XHRs sequentially and uses the array concat method to merge the resolved arrays into a single array.
Usage:
$scope.loadAllPagedItems(category, pages, itemsPerPages)
.then(function(finalArray) {
console.log(finalArray);
}).catch(function(response) {
console.log("ERROR ",response.status);
throw response;
});

Name database child in Firebase?

This is the code I have.
function saveTrip()
{
routeData.clear();
for (var i = 0; i < dirDisplay.directions.routes[0].legs.length; i++) {
for (var j = 0; j < dirDisplay.directions.routes[0].legs[i].steps.length; j++) {
routeData.push(dirDisplay.directions.routes[0].legs[i].steps[j].path);
}
}
routeLinesRef.push(routeData, function(error){
if (error) {
$('#savedSpan').html('Data could not be saved.' + error);
} else {
$('#savedSpan').html('Data saved successfully!');
}
});
}
Array.prototype.clear = function() {
this.splice(0, this.length);
};
routeLinesRef.limit(10).on('child_added', function(snapshot)
{
// loop over each route we get from firebase
route = snapshot.val();
What function should be written to write into the hierarchy as shown in the image?
id = snapshot.name();
// make an array that is initially blank
// It will contain all the latitude and longitudes of each point on in the route
var routeCoordinates = [];
// This loops over each point on the route
for (var i=0; i<route.length; i++)
{
for (var j in route[i])
{
if (j==0 && i>0)
{
continue
}
else
{
This part just takes each point on the route, and converts it into
a google maps LatLng object. For example, if the data is [58.23, 18.8], it will do:
new google.maps.LatLng(58.23, 18.8) to it, which turns it into a format that google maps likes.
if (route[i][j].lb && route[i][j].mb) {
routeCoordinates.push(new google.maps.LatLng
(route[i][j].lb, route[i][j].mb));
//console.log(j + ' ' + snapshot.val()[route][i][j].lb, snapshot.val()[route][i][j].mb);
}
}
}
}
What should I do? I can't find any tutorial or anything.

JavaScript timer is resetting while refreshing the page

I got a count down timer script.. I'm going to use it for a online examination.. But now the problem is it is resetting while refreshing the page...
Any idea to prevent the resetting the time and continue without any problem if they refresh the page too?
here is the code
<script>
var mins;
var secs;
function cd() {
mins = 1 * m("2"); // change minutes here
secs = 0 + s(":01"); // change seconds here (always add an additional second to your total)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
document.getElementById("disp").innerHTML=dis(mins,secs); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
window.alert("Time is up. Press OK to continue."); // change timeout message as required
// window.location = "yourpage.htm" // redirects to specified page once timer ends and ok button is pressed
} else {
cd = setTimeout("redo()",1000);
}
}
function init() {
cd();
}
window.onload = init;
</script>
If the page is refreshed, all you javascript code is re-executed. This is normal behaviour.
If you absolutely need to continue where you left, you can use the local storage API (only available in modern browsers) to store the time (every second you update the value).
When the page is loaded, you can then check if the value exists in Local storage, and start from where you were.
Are you sure you need this behaviour BTW?

Resources