javascript - How to write function in async mode when $rootscope.broadcast is being used in an infinite loop? -
i have following function gets called @ least 10 times in second. every time have around 100 records same except it's lastseentime, readcount. since simulator know behaviour in real time, no of records in array may vary 100 - 1000. may or may not same. need add distinct records tagstore being displayed in ui thereafter.
$scope.$on('getreadtags', function (event, tags) { if (($scope.tagstore == null || $scope.tagstore.length == 0) && tags.length != 0) { $scope.tagstore = tags; } else { (var = 0; < tags.length; i++) { var notfound = true; (var j = 0; j < $scope.tagstore.length; j++) { if (tags[i].tagid == $scope.tagstore[j].tagid) { $scope.tagstore[j].readcount += tags[i].readcount; $scope.tagstore[j].lastseentime = tags[i].lastseentime; $scope.tagstore[j].discoverytime = tags[i].discoverytime; notfound = false; break; } } if (!notfound) { $scope.tagstore.push(tags[i]); } } } $scope.$apply(); });
when runs code, browser gets stuck. noticed cpu, ram utilization shooting high. need method should called after first method has completed it's execution.
you invoking multiple digest cycles 1 after other, , makes cpu , memory consumption jump sky, , hang browser.
use $applyasync
instead of $scope.$apply();
collect multiple $apply
1 $digest cycle. can see in documentation (bold area):
$applyasync([exp]); schedule invocation of $apply occur @ later time. actual time difference varies across browsers, typically around ~10 milliseconds.
this can used queue multiple expressions need be evaluated in same digest.
this loop for (var j = 0; j < $scope.tagstore.length; j++) {
redundant, iterates whole list of tags, every tag inserted, , half of on average every tag updated. instead:
var tagsmap; $scope.$on('getreadtags', function (event, tags) { if (($scope.tagstore == null || $scope.tagstore.length == 0) && tags.length != 0) { $scope.tagstore = tags; tagsmap = tags.reduce(function(obj, item) { obj[item.tagid] = item; // create map of tags }, {}); } else { (var = 0; < tags.length; i++) { if(tagsmap[tags[i].tagid]) { // if tag exists in map, update tag tagsmap[tags[i].tagid].readcount += tags[i].readcount; tagsmap[tags[i].tagid].lastseentime = tags[i].lastseentime; tagsmap[tags[i].tagid].discoverytime = tags[i].discoverytime; } else { // if tag doesn't exist, push scope, , add tagsmap $scope.tagstore.push(tags[i]); tagsmap[tags[i].tagid] = tags[i]; } } } $scope.$applyasync(); });
Comments
Post a Comment